diff --git a/.jshintrc b/.jshintrc
new file mode 100644
index 0000000..4a20e4c
--- /dev/null
+++ b/.jshintrc
@@ -0,0 +1,3 @@
+{
+ "esnext": true
+}
\ No newline at end of file
diff --git a/build.js b/build.js
new file mode 100644
index 0000000..3a8d2ca
--- /dev/null
+++ b/build.js
@@ -0,0 +1,624 @@
+"use strict";
+
+"format register";
+(function (global) {
+ var defined = {};
+
+ // indexOf polyfill for IE8
+ var indexOf = Array.prototype.indexOf || function (item) {
+ for (var i = 0,
+ l = this.length; i < l; i++) if (this[i] === item) return i;
+ return -1;
+ };
+
+ function dedupe(deps) {
+ var newDeps = [];
+ for (var i = 0,
+ l = deps.length; i < l; i++) if (indexOf.call(newDeps, deps[i]) == -1) newDeps.push(deps[i]);
+ return newDeps;
+ }
+
+ function register(name, deps, declare, execute) {
+ if (typeof name != "string") throw "System.register provided no module name";
+
+ var entry;
+
+ // dynamic
+ if (typeof declare == "boolean") {
+ entry = {
+ declarative: false,
+ deps: deps,
+ execute: execute,
+ executingRequire: declare
+ };
+ } else {
+ // ES6 declarative
+ entry = {
+ declarative: true,
+ deps: deps,
+ declare: declare
+ };
+ }
+
+ entry.name = name;
+
+ // we never overwrite an existing define
+ if (!defined[name]) defined[name] = entry;
+
+ entry.deps = dedupe(entry.deps);
+
+ // we have to normalize dependencies
+ // (assume dependencies are normalized for now)
+ // entry.normalizedDeps = entry.deps.map(normalize);
+ entry.normalizedDeps = entry.deps;
+ }
+
+ function buildGroups(entry, groups) {
+ groups[entry.groupIndex] = groups[entry.groupIndex] || [];
+
+ if (indexOf.call(groups[entry.groupIndex], entry) != -1) return;
+
+ groups[entry.groupIndex].push(entry);
+
+ for (var i = 0,
+ l = entry.normalizedDeps.length; i < l; i++) {
+ var depName = entry.normalizedDeps[i];
+ var depEntry = defined[depName];
+
+ // not in the registry means already linked / ES6
+ if (!depEntry || depEntry.evaluated) continue;
+
+ // now we know the entry is in our unlinked linkage group
+ var depGroupIndex = entry.groupIndex + (depEntry.declarative != entry.declarative);
+
+ // the group index of an entry is always the maximum
+ if (depEntry.groupIndex === undefined || depEntry.groupIndex < depGroupIndex) {
+ // if already in a group, remove from the old group
+ if (depEntry.groupIndex !== undefined) {
+ groups[depEntry.groupIndex].splice(indexOf.call(groups[depEntry.groupIndex], depEntry), 1);
+
+ // if the old group is empty, then we have a mixed depndency cycle
+ if (groups[depEntry.groupIndex].length == 0) throw new TypeError("Mixed dependency cycle detected");
+ }
+
+ depEntry.groupIndex = depGroupIndex;
+ }
+
+ buildGroups(depEntry, groups);
+ }
+ }
+
+ function link(name) {
+ var startEntry = defined[name];
+
+ startEntry.groupIndex = 0;
+
+ var groups = [];
+
+ buildGroups(startEntry, groups);
+
+ var curGroupDeclarative = !!startEntry.declarative == groups.length % 2;
+ for (var i = groups.length - 1; i >= 0; i--) {
+ var group = groups[i];
+ for (var j = 0; j < group.length; j++) {
+ var entry = group[j];
+
+ // link each group
+ if (curGroupDeclarative) linkDeclarativeModule(entry);else linkDynamicModule(entry);
+ }
+ curGroupDeclarative = !curGroupDeclarative;
+ }
+ }
+
+ // module binding records
+ var moduleRecords = {};
+ function getOrCreateModuleRecord(name) {
+ return moduleRecords[name] || (moduleRecords[name] = {
+ name: name,
+ dependencies: [],
+ exports: {}, // start from an empty module and extend
+ importers: []
+ });
+ }
+
+ function linkDeclarativeModule(entry) {
+ // only link if already not already started linking (stops at circular)
+ if (entry.module) return;
+
+ var module = entry.module = getOrCreateModuleRecord(entry.name);
+ var exports = entry.module.exports;
+
+ var declaration = entry.declare.call(global, function (name, value) {
+ module.locked = true;
+ exports[name] = value;
+
+ for (var i = 0,
+ l = module.importers.length; i < l; i++) {
+ var importerModule = module.importers[i];
+ if (!importerModule.locked) {
+ var importerIndex = indexOf.call(importerModule.dependencies, module);
+ importerModule.setters[importerIndex](exports);
+ }
+ }
+
+ module.locked = false;
+ return value;
+ });
+
+ module.setters = declaration.setters;
+ module.execute = declaration.execute;
+
+ if (!module.setters || !module.execute) throw new TypeError("Invalid System.register form for " + entry.name);
+
+ // now link all the module dependencies
+ for (var i = 0,
+ l = entry.normalizedDeps.length; i < l; i++) {
+ var depName = entry.normalizedDeps[i];
+ var depEntry = defined[depName];
+ var depModule = moduleRecords[depName];
+
+ // work out how to set depExports based on scenarios...
+ var depExports;
+
+ if (depModule) {
+ depExports = depModule.exports;
+ } else if (depEntry && !depEntry.declarative) {
+ depExports = { "default": depEntry.module.exports, __useDefault: true };
+ }
+ // in the module registry
+ else if (!depEntry) {
+ depExports = load(depName);
+ }
+ // we have an entry -> link
+ else {
+ linkDeclarativeModule(depEntry);
+ depModule = depEntry.module;
+ depExports = depModule.exports;
+ }
+
+ // only declarative modules have dynamic bindings
+ if (depModule && depModule.importers) {
+ depModule.importers.push(module);
+ module.dependencies.push(depModule);
+ } else module.dependencies.push(null);
+
+ // run the setter for this dependency
+ if (module.setters[i]) module.setters[i](depExports);
+ }
+ }
+
+ // An analog to loader.get covering execution of all three layers (real declarative, simulated declarative, simulated dynamic)
+ function getModule(name) {
+ var exports;
+ var entry = defined[name];
+
+ if (!entry) {
+ exports = load(name);
+ if (!exports) throw new Error("Unable to load dependency " + name + ".");
+ } else {
+ if (entry.declarative) ensureEvaluated(name, []);else if (!entry.evaluated) linkDynamicModule(entry);
+
+ exports = entry.module.exports;
+ }
+
+ if ((!entry || entry.declarative) && exports && exports.__useDefault) return exports["default"];
+
+ return exports;
+ }
+
+ function linkDynamicModule(entry) {
+ if (entry.module) return;
+
+ var exports = {};
+
+ var module = entry.module = { exports: exports, id: entry.name };
+
+ // AMD requires execute the tree first
+ if (!entry.executingRequire) {
+ for (var i = 0,
+ l = entry.normalizedDeps.length; i < l; i++) {
+ var depName = entry.normalizedDeps[i];
+ var depEntry = defined[depName];
+ if (depEntry) linkDynamicModule(depEntry);
+ }
+ }
+
+ // now execute
+ entry.evaluated = true;
+ var output = entry.execute.call(global, function (name) {
+ for (var i = 0,
+ l = entry.deps.length; i < l; i++) {
+ if (entry.deps[i] != name) continue;
+ return getModule(entry.normalizedDeps[i]);
+ }
+ throw new TypeError("Module " + name + " not declared as a dependency.");
+ }, exports, module);
+
+ if (output) module.exports = output;
+ }
+
+ /*
+ * Given a module, and the list of modules for this current branch,
+ * ensure that each of the dependencies of this module is evaluated
+ * (unless one is a circular dependency already in the list of seen
+ * modules, in which case we execute it)
+ *
+ * Then we evaluate the module itself depth-first left to right
+ * execution to match ES6 modules
+ */
+ function ensureEvaluated(moduleName, seen) {
+ var entry = defined[moduleName];
+
+ // if already seen, that means it's an already-evaluated non circular dependency
+ if (entry.evaluated || !entry.declarative) return;
+
+ // this only applies to declarative modules which late-execute
+
+ seen.push(moduleName);
+
+ for (var i = 0,
+ l = entry.normalizedDeps.length; i < l; i++) {
+ var depName = entry.normalizedDeps[i];
+ if (indexOf.call(seen, depName) == -1) {
+ if (!defined[depName]) load(depName);else ensureEvaluated(depName, seen);
+ }
+ }
+
+ if (entry.evaluated) return;
+
+ entry.evaluated = true;
+ entry.module.execute.call(global);
+ }
+
+ // magical execution function
+ var modules = {};
+ function load(name) {
+ if (modules[name]) return modules[name];
+
+ var entry = defined[name];
+
+ // first we check if this module has already been defined in the registry
+ if (!entry) throw "Module " + name + " not present.";
+
+ // recursively ensure that the module and all its
+ // dependencies are linked (with dependency group handling)
+ link(name);
+
+ // now handle dependency execution in correct order
+ ensureEvaluated(name, []);
+
+ // remove from the registry
+ defined[name] = undefined;
+
+ var module = entry.declarative ? entry.module.exports : { "default": entry.module.exports, __useDefault: true };
+
+ // return the defined module object
+ return modules[name] = module;
+ };
+
+ return function (main, declare) {
+ var System;
+
+ // if there's a system loader, define onto it
+ if (typeof System != "undefined" && System.register) {
+ declare(System);
+ System["import"](main);
+ }
+ // otherwise, self execute
+ else {
+ declare(System = {
+ register: register,
+ get: load,
+ set: function (name, module) {
+ modules[name] = module;
+ },
+ newModule: function (module) {
+ return module;
+ },
+ global: global
+ });
+ load(main);
+ }
+ };
+})(typeof window != "undefined" ? window : global)
+/* ('mainModule', function(System) {
+ System.register(...);
+}); */
+
+("src/main", function (System) {
+
+
+
+
+ System.register("src/lib/vector", [], true, function (require, exports, module) {
+ var global = System.global,
+ __define = global.define;
+ global.define = undefined;
+ function Vector() {
+ var x = arguments[0] === undefined ? 0 : arguments[0];
+ var y = arguments[1] === undefined ? 0 : arguments[1];
+ var z = arguments[2] === undefined ? 0 : arguments[2];
+ if (!(this instanceof Vector)) return new Vector(x, y, z);
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ return this;
+ }
+ Vector.prototype.invert = function () {
+ this.x = -this.x;
+ this.y = -this.y;
+ this.z = -this.z;
+ };
+ Vector.prototype.magnitude = function () {
+ return Math.sqrt(this.magnitude2());
+ };
+ Vector.prototype.magnitude2 = function () {
+ return this.x * this.x + this.y * this.y + this.z * this.z;
+ };
+ Vector.prototype.normalize = function () {
+ var magnitude = this.magnitude();
+ if (this.magnitude() <= 0) return this;
+ return this.scalar(1 / magnitude);
+ };
+ Vector.prototype.scalar = function () {
+ var n = arguments[0] === undefined ? 1 : arguments[0];
+ this.x *= n;
+ this.y *= n;
+ this.z *= n;
+ return this;
+ };
+ Vector.prototype.clone = function () {
+ return new Vector(this.x, this.y, this.z);
+ };
+ Vector.prototype.add = function (vec) {
+ this.x += vec.x;
+ this.y += vec.y;
+ this.z += vec.z;
+ return this;
+ };
+ Vector.prototype.component = function (vec) {
+ this.x *= vec.x;
+ this.y *= vec.y;
+ this.z *= vec.z;
+ return this;
+ };
+ Vector.prototype.dot = function (vec) {
+ return this.x * vec.x + this.y * vec.y + this.z * vec.z;
+ };
+ Vector.prototype.cross = function (vec) {
+ this.x = this.y * vec.z - this.z * vec.y;
+ this.y = this.x * vec.z - this.z * vec.x;
+ this.z = this.x * vec.y - this.y * vec.x;
+ return this;
+ };
+ Vector.orthonormal = function (v1, v2) {
+ var v1xv2 = v1.clone().cross(v2);
+ v2 = v1xv2.clone().cross(v1);
+ return [v1.normalize(), v2.normalize(), v1xv2.normalize()];
+ };
+ function randomRange(min, max) {
+ return Math.random() * (max - min) + min;
+ }
+ Vector.random = function (x, y, z) {
+ return new Vector(randomRange(x[0], x[1]), randomRange(y[0], y[1]), randomRange(z[0], z[1]));
+ };
+ function killNaN(a) {
+ if (isNaN(a)) return 0;
+ return a;
+ }
+ module.exports = Vector;
+ global.define = __define;
+ return module.exports;
+ });
+
+
+
+ System.register("src/lib/particle", ["src/lib/vector", "src/main"], function ($__export) {
+ "use strict";
+ var __moduleName = "src/lib/particle";
+ var Vector, Bolt;
+ function Particle() {
+ var properties = arguments[0] !== void 0 ? arguments[0] : {};
+ if (!(this instanceof Particle)) return new Particle(properties);
+ this.position = properties.position || new Vector();
+ this.velocity = properties.velocity || new Vector();
+ this.acceleration = properties.acceleration || new Vector();
+ this.damping = properties.damping || 0.95;
+ this.mass = properties.mass || 10;
+ Bolt.objects.push(this);
+ }
+ return {
+ setters: [function (m) {
+ Vector = m["default"];
+ }, function (m) {
+ Bolt = m["default"];
+ }],
+ execute: function () {
+ Object.defineProperties(Particle.prototype, { mass: {
+ configurable: true,
+ enumerable: true,
+ get: function () {
+ return 1 / this.inverseMass;
+ },
+ set: function (val) {
+ if (val === 0) this.inverseMass = Infinity;else this.inverseMass = 1 / val;
+ }
+ } });
+ Particle.prototype.destroy = function () {
+ return Bolt.objects.splice(Bolt.objects.indexOf(this), 1);
+ };
+ $__export("default", Particle);
+ }
+ };
+ });
+
+
+
+ System.register("src/lib/gravity", ["src/lib/vector"], function ($__export) {
+ "use strict";
+ var __moduleName = "src/lib/gravity";
+ var Vector, Gravity;
+ return {
+ setters: [function (m) {
+ Vector = m["default"];
+ }],
+ execute: function () {
+ Gravity = {
+ between: function (o1, o2) {
+ var mass = o1.mass * o2.mass;
+ return new Vector(Math.pow(o1.position.x - o2.position.x, 2), Math.pow(o1.position.y - o2.position.y, 2), Math.pow(o1.position.z - o2.position.z, 2));
+ },
+ globalMass: 10,
+ global: function (mass, g) {
+ return new Vector(0, mass * (g || this.globalMass), 0);
+ }
+ };
+ $__export("default", Gravity);
+ }
+ };
+ });
+
+
+
+ System.register("src/lib/frames", [], function ($__export) {
+ "use strict";
+ var __moduleName = "src/lib/frames";
+ var Frames;
+ return {
+ setters: [],
+ execute: function () {
+ Frames = {
+ lastFrame: 0,
+ elapsed: 0,
+ average: 0,
+ fps: 0,
+ tick: function (now) {
+ this.elapsed = (now - (this.lastFrame || now)) / 1000;
+ this.lastFrame = now;
+ if (this.elapsed > 0) this.fps = Math.round(1 / this.elapsed);
+ this.average = Math.round((this.average + this.fps) / 2);
+ return this.average;
+ }
+ };
+ $__export("default", Frames);
+ }
+ };
+ });
+
+
+
+ System.register("src/lib/play", ["src/lib/frames", "src/lib/gravity", "src/main"], function ($__export) {
+ "use strict";
+ var __moduleName = "src/lib/play";
+ var Frames, Gravity, Bolt, reqAnimFrame, cancelAnimFrame, Play;
+ return {
+ setters: [function (m) {
+ Frames = m["default"];
+ }, function (m) {
+ Gravity = m["default"];
+ }, function (m) {
+ Bolt = m["default"];
+ }],
+ execute: function () {
+ reqAnimFrame = requestAnimationFrame || webkitRequestAnimationFrame || mozRequestAnimationFrame || oRequestAnimationFrame || msRequestAnimationFrame, cancelAnimFrame = cancelAnimationFrame || webkitCancelAnimationFrame || mozCancelAnimationFrame || oCancelAnimationFrame || msCancelAnimationFrame;
+ Play = {
+ playing: false,
+ start: function (fn) {
+ Frames.tick(Date.now());
+ var canvas = typeof Bolt.configs.canvas === "function" ? Bolt.configs.canvas() : Bolt.configs.canvas;
+ Bolt._canvas = canvas;
+ var ctx = canvas.getContext("2d");
+ (function loop() {
+ reqAnimFrame(function (now) {
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.fillStyle = "black";
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ var avg = Frames.tick(now);
+ for (var i = 0,
+ len = Bolt.objects.length; i < len; i++) {
+ var object = Bolt.objects[i];
+ if (Bolt.configs.globalGravity) {
+ var force = Gravity.global(object.inverseMass);
+ object.position.add(object.velocity.clone().scalar(Frames.elapsed));
+ var acc = object.acceleration.clone();
+ acc.add(force);
+ object.velocity.add(acc.scalar(Frames.elapsed));
+ object.velocity.scalar(Math.pow(object.damping, Frames.elapsed));
+ ctx.beginPath();
+ ctx.fillStyle = object.color;
+ ctx.arc(object.position.x, object.position.y, object.mass, 0, 2 * Math.PI);
+ ctx.fill();
+ }
+ }
+ if (fn) fn.apply(this, arguments);
+ loop();
+ });
+ })();
+ this.playing = true;
+ return new Promise(function (resolve) {
+ setTimeout(resolve, 5);
+ });
+ },
+ stop: function () {
+ cancelAnimFrame();
+ this.playing = false;
+ }
+ };
+ $__export("default", Play);
+ }
+ };
+ });
+
+
+
+ System.register("src/main", ["src/lib/vector", "src/lib/particle", "src/lib/gravity", "src/lib/frames", "src/lib/play"], function ($__export) {
+ "use strict";
+ var __moduleName = "src/main";
+ var Vector, Particle, Gravity, Frames, Play, Bolt;
+ return {
+ setters: [function (m) {
+ Vector = m["default"];
+ }, function (m) {
+ Particle = m["default"];
+ }, function (m) {
+ Gravity = m["default"];
+ }, function (m) {
+ Frames = m["default"];
+ }, function (m) {
+ Play = m["default"];
+ }],
+ execute: function () {
+ Bolt = {
+ configs: {
+ globalGravity: true,
+ canvas: function () {
+ var canvas = document.createElement("canvas");
+ canvas.width = window.innerWidth;
+ canvas.height = window.innerHeight;
+ document.body.appendChild(canvas);
+ return canvas;
+ }
+ },
+ config: function (o) {
+ for (var i in o) {
+ this.configs[i] = o[i];
+ }
+ return this.configs;
+ },
+ objects: [],
+ Vector: Vector,
+ Particle: Particle,
+ Gravity: Gravity,
+ Frames: Frames,
+ Play: Play
+ };
+ window.Bolt = Bolt;
+ $__export("default", Bolt);
+ }
+ };
+ });
+
+
+
+});
+//# sourceMappingURL=build.js.map
diff --git a/build.js.map b/build.js.map
new file mode 100644
index 0000000..b65cf0c
--- /dev/null
+++ b/build.js.map
@@ -0,0 +1 @@
+{"version":3,"sources":["src/lib/vector.js","src/lib/particle.js","src/lib/gravity.js","src/lib/frames.js","src/lib/play.js","src/main.js"],"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AAA,QAAO,cAAc,AAAC,CAAC,QAAO,CAAC,CAAC;AAC7C,iBAAK,MAAM,EAAI,CAAA,MAAK,WAAW,CAAC;AAChC,iBAAK,OAAO,EAAI,CAAA,MAAK,YAAY,CAAC;AAElC,mBAAO,KAAK,YAAY,AAAC,CAAC,MAAK,CAAC,CAAC;AAEjC,iBAAO,OAAK,CAAC;UACf;AAAA,QACF;AAEA,aAAK,CAAG,UAAS,CAAA,CAAG;AAClB,cAAQ,GAAA,CAAA,CAAA,CAAA,EAAK,EAAA,CAAG;AACd,eAAG,QAAQ,CAAE,CAAA,CAAC,EAAI,CAAA,CAAA,CAAE,CAAA,CAAC,CAAC;UACxB;AAAA,AACA,eAAO,CAAA,IAAG,QAAQ,CAAC;QACrB;AAEA,cAAM,CAAG,GAAC;AAEV,aAAK,CAAG,OAAK;AACb,eAAO,CAAG,SAAO;AACjB,cAAM,CAAG,QAAM;AACf,aAAK,CAAG,OAAK;AACb,WAAG,CAAG,KAAG;AAAA,MACX;AAEA,WAAK,KAAK,EAAI,KAAG,CAAC;yBAEH,KAAG;;;;AAAC","file":"/home/mahdi/Documents/Workshop/bolt/build.js"}
\ No newline at end of file
diff --git a/config.js b/config.js
new file mode 100644
index 0000000..dcc105d
--- /dev/null
+++ b/config.js
@@ -0,0 +1,9 @@
+System.config({
+ "paths": {
+ "*": "*.js",
+ "Bolt/*": "src/*.js",
+ "npm:*": "jspm_packages/npm/*.js",
+ "bolt/*": "src/*.js"
+ }
+});
+
diff --git a/demos/fireworks/demo.js b/demos/fireworks/demo.js
new file mode 100644
index 0000000..01b1259
--- /dev/null
+++ b/demos/fireworks/demo.js
@@ -0,0 +1,55 @@
+function Firework(props) {
+ var particle = Bolt.Particle(props);
+ particle.type = props.type || 0;
+ particle.age = Math.random() * (5 - 3) + 3;
+ particle.damping = 0.93;
+ particle.velocity = props.velocity || Bolt.Vector.random([-8, 8], [-60, -12], [-5, 0]);
+ particle.color = props.color;
+ return particle;
+}
+
+var fireworks = [];
+
+var count = 0;
+
+Bolt.Play.start(function() {
+
+ count++;
+ if(count === 8) {
+ fireworks.push(new Firework({
+ type: 0,
+ position: Bolt.Vector(Bolt._canvas.width/2, Bolt._canvas.height/2, 0),
+ color: '#FF3636',
+ mass: 2
+ }));
+ count = 0;
+ }
+
+ for(var i = 0, len = fireworks.length; i < len; i++) {
+ var fw = fireworks[i];
+ fw.age -= Bolt.Frames.elapsed;
+ if(fw.age < 0) {
+ fw.destroy();
+ fireworks.splice(i, 1);
+ i--;
+ len--;
+
+ if(fw.type === 1) continue;
+
+ for(var x = 0; x < 5; x++) {
+ var vel = fw.velocity.clone().add(Bolt.Vector.random([-8, 8], [-10, 10], [-5, 5]));
+ var childFirework = new Firework({
+ type: 1,
+ position: fw.position.clone(),
+ velocity: vel,
+ color: '#FFA400',
+ mass: 1
+ });
+ fireworks.push(childFirework);
+ }
+ }
+ }
+
+}).then(function() {
+
+});
\ No newline at end of file
diff --git a/demos/fireworks/index.html b/demos/fireworks/index.html
new file mode 100644
index 0000000..84a6905
--- /dev/null
+++ b/demos/fireworks/index.html
@@ -0,0 +1,13 @@
+
+
+
+
+ Bolt
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jspm_packages/.loaderversions b/jspm_packages/.loaderversions
new file mode 100644
index 0000000..959cd17
--- /dev/null
+++ b/jspm_packages/.loaderversions
@@ -0,0 +1 @@
+0.11,0.11,0.0.79
\ No newline at end of file
diff --git a/jspm_packages/es6-module-loader.js b/jspm_packages/es6-module-loader.js
new file mode 100644
index 0000000..9d5bd14
--- /dev/null
+++ b/jspm_packages/es6-module-loader.js
@@ -0,0 +1,8 @@
+/*
+ * es6-module-loader v0.11.2
+ * https://github.com/ModuleLoader/es6-module-loader
+ * Copyright (c) 2015 Guy Bedford, Luke Hoban, Addy Osmani; Licensed MIT
+ */
+
+!function(a){"object"==typeof exports?module.exports=a():"function"==typeof define&&define.amd?define(a):"undefined"!=typeof window?window.Promise=a():"undefined"!=typeof global?global.Promise=a():"undefined"!=typeof self&&(self.Promise=a())}(function(){var a;return function b(a,c,d){function e(g,h){if(!c[g]){if(!a[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};a[g][0].call(j.exports,function(b){var c=a[g][1][b];return e(c?c:b)},j,j.exports,b,a,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g=0&&(n.splice(b,1),l("Handled previous rejection ["+a.id+"] "+e.formatObject(a.value)))}function h(a,b){m.push(a,b),null===o&&(o=d(i,0))}function i(){for(o=null;m.length>0;)m.shift()(m.shift())}var j,k=c,l=c;"undefined"!=typeof console&&(j=console,k="undefined"!=typeof j.error?function(a){j.error(a)}:function(a){j.log(a)},l="undefined"!=typeof j.info?function(a){j.info(a)}:function(a){j.log(a)}),a.onPotentiallyUnhandledRejection=function(a){h(f,a)},a.onPotentiallyUnhandledRejectionHandled=function(a){h(g,a)},a.onFatalRejection=function(a){h(b,a.value)};var m=[],n=[],o=null;return a}})}("function"==typeof a&&a.amd?a:function(a){c.exports=a(b)})},{"../env":5,"../format":6}],5:[function(b,c){!function(a){"use strict";a(function(a){function b(){return"undefined"!=typeof process&&null!==process&&"function"==typeof process.nextTick}function c(){return"function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver}function d(a){function b(){var a=c;c=void 0,a()}var c,d=document.createTextNode(""),e=new a(b);e.observe(d,{characterData:!0});var f=0;return function(a){c=a,d.data=f^=1}}var e,f="undefined"!=typeof setTimeout&&setTimeout,g=function(a,b){return setTimeout(a,b)},h=function(a){return clearTimeout(a)},i=function(a){return f(a,0)};if(b())i=function(a){return process.nextTick(a)};else if(e=c())i=d(e);else if(!f){var j=a,k=j("vertx");g=function(a,b){return k.setTimer(b,a)},h=k.cancelTimer,i=k.runOnLoop||k.runOnContext}return{setTimer:g,clearTimer:h,asap:i}})}("function"==typeof a&&a.amd?a:function(a){c.exports=a(b)})},{}],6:[function(b,c){!function(a){"use strict";a(function(){function a(a){var c="object"==typeof a&&null!==a&&a.stack?a.stack:b(a);return a instanceof Error?c:c+" (WARNING: non-Error used)"}function b(a){var b=String(a);return"[object Object]"===b&&"undefined"!=typeof JSON&&(b=c(a,b)),b}function c(a,b){try{return JSON.stringify(a)}catch(c){return b}}return{formatError:a,formatObject:b,tryStringify:c}})}("function"==typeof a&&a.amd?a:function(a){c.exports=a()})},{}],7:[function(b,c){!function(a){"use strict";a(function(){return function(a){function b(a,b){this._handler=a===t?b:c(a)}function c(a){function b(a){e.resolve(a)}function c(a){e.reject(a)}function d(a){e.notify(a)}var e=new v;try{a(b,c,d)}catch(f){c(f)}return e}function d(a){return I(a)?a:new b(t,new w(q(a)))}function e(a){return new b(t,new w(new z(a)))}function f(){return Z}function g(){return new b(t,new v)}function h(a,b){var c=new v(a.receiver,a.join().context);return new b(t,c)}function i(a){return k(S,null,a)}function j(a,b){return k(N,a,b)}function k(a,c,d){function e(b,e,g){g.resolved||l(d,f,b,a(c,e,b),g)}function f(a,b,c){k[a]=b,0===--j&&c.become(new y(k))}for(var g,h="function"==typeof c?e:f,i=new v,j=d.length>>>0,k=new Array(j),m=0;m0?b(c,f.value,e):(e.become(f),m(a,c+1,f))}else b(c,d,e)}function m(a,b,c){for(var d=b;dc&&a._unreport()}}function o(a){return"object"!=typeof a||null===a?e(new TypeError("non-iterable passed to race()")):0===a.length?f():1===a.length?d(a[0]):p(a)}function p(a){var c,d,e,f=new v;for(c=0;c0||"function"!=typeof b&&0>e)return new this.constructor(t,d);var f=this._beget(),g=f._handler;return d.chain(g,d.receiver,a,b,c),f},b.prototype["catch"]=function(a){return this.then(void 0,a)},b.prototype._beget=function(){return h(this._handler,this.constructor)},b.all=i,b.race=o,b._traverse=j,b._visitRemaining=m,t.prototype.when=t.prototype.become=t.prototype.notify=t.prototype.fail=t.prototype._unreport=t.prototype._report=T,t.prototype._state=0,t.prototype.state=function(){return this._state},t.prototype.join=function(){for(var a=this;void 0!==a.handler;)a=a.handler;return a},t.prototype.chain=function(a,b,c,d,e){this.when({resolver:a,receiver:b,fulfilled:c,rejected:d,progress:e})},t.prototype.visit=function(a,b,c,d){this.chain(W,a,b,c,d)},t.prototype.fold=function(a,b,c,d){this.when(new H(a,b,c,d))},R(t,u),u.prototype.become=function(a){a.fail()};var W=new u;R(t,v),v.prototype._state=0,v.prototype.resolve=function(a){this.become(q(a))},v.prototype.reject=function(a){this.resolved||this.become(new z(a))},v.prototype.join=function(){if(!this.resolved)return this;for(var a=this;void 0!==a.handler;)if(a=a.handler,a===this)return this.handler=C();return a},v.prototype.run=function(){var a=this.consumers,b=this.join();this.consumers=void 0;for(var c=0;cf;f++)if(e=b.loads[f],e.name==c)return e;return e=a(c),b.loads.push(e),d(b,e),e})}function d(a,b){e(a,b,A.resolve().then(function(){return a.loaderObj.locate({name:b.name,metadata:b.metadata})}))}function e(a,b,c){f(a,b,c.then(function(c){return"loading"==b.status?(b.address=c,a.loaderObj.fetch({name:b.name,metadata:b.metadata,address:c})):void 0}))}function f(a,b,d){d.then(function(c){return"loading"==b.status?a.loaderObj.translate({name:b.name,metadata:b.metadata,address:b.address,source:c}):void 0}).then(function(c){return"loading"==b.status?(b.source=c,a.loaderObj.instantiate({name:b.name,metadata:b.metadata,address:b.address,source:c})):void 0}).then(function(d){if("loading"==b.status){if(void 0===d)b.address=b.address||"",b.isDeclarative=!0,a.loaderObj.parse(b);else{if("object"!=typeof d)throw TypeError("Invalid instantiate return value");b.depsList=d.deps||[],b.execute=d.execute,b.isDeclarative=!1}b.dependencies=[];for(var e=b.depsList,f=[],g=0,h=e.length;h>g;g++)(function(d,e){f.push(c(a,d,b.name,b.address).then(function(a){if(b.dependencies[e]={key:d,value:a.name},"linked"!=a.status)for(var c=b.linkSets.concat([]),f=0,g=c.length;g>f;f++)i(c[f],a)}))})(e[g],g);return A.all(f)}}).then(function(){b.status="loaded";for(var a=b.linkSets.concat([]),c=0,d=a.length;d>c;c++)k(a[c],b)})["catch"](function(a){b.status="failed",b.exception=a;for(var c=b.linkSets.concat([]),d=0,e=c.length;e>d;d++)l(c[d],b,a)})}function g(b){return function(c){var g=b.loader,i=b.moduleName,j=b.step;if(g.modules[i])throw new TypeError('"'+i+'" already exists in the module table');for(var k,l=0,m=g.loads.length;m>l;l++)if(g.loads[l].name==i)return k=g.loads[l],k.linkSets[0].done.then(function(){c(k)});var n=a(i);n.metadata=b.moduleMetadata;var o=h(g,n);g.loads.push(n),c(o.done),"locate"==j?d(g,n):"fetch"==j?e(g,n,A.resolve(b.moduleAddress)):(n.address=b.moduleAddress,f(g,n,A.resolve(b.moduleSource)))}}function h(a,b){var c={loader:a,loads:[],startingLoad:b,loadingCount:0};return c.done=new A(function(a,b){c.resolve=a,c.reject=b}),i(c,b),c}function i(a,b){for(var c=0,d=a.loads.length;d>c;c++)if(a.loads[c]==b)return;a.loads.push(b),b.linkSets.push(a),"loaded"!=b.status&&a.loadingCount++;for(var e=a.loader,c=0,d=b.dependencies.length;d>c;c++){var f=b.dependencies[c].value;if(!e.modules[f])for(var g=0,h=e.loads.length;h>g;g++)if(e.loads[g].name==f){i(a,e.loads[g]);break}}}function j(a){var b=!1;try{p(a,function(c,d){l(a,c,d),b=!0})}catch(c){l(a,null,c),b=!0}return b}function k(a,b){if(a.loadingCount--,!(a.loadingCount>0)){var c=a.startingLoad;if(a.loader.loaderObj.execute===!1){for(var d=[].concat(a.loads),e=0,f=d.length;f>e;e++){var b=d[e];b.module=b.isDeclarative?{name:b.name,module:E({}),evaluated:!0}:{module:E({})},b.status="linked",m(a.loader,b)}return a.resolve(c)}var g=j(a);g||a.resolve(c)}}function l(a,b,c){var d=a.loader;a.loads[0].name!=b.name&&(c=w(c,'Error loading "'+b.name+'" from "'+a.loads[0].name+'" at '+(a.loads[0].address||"")+"\n")),c=w(c,'Error loading "'+b.name+'" at '+(b.address||"")+"\n");for(var e=a.loads.concat([]),f=0,g=e.length;g>f;f++){var b=e[f];d.loaderObj.failed=d.loaderObj.failed||[],-1==B.call(d.loaderObj.failed,b)&&d.loaderObj.failed.push(b);var h=B.call(b.linkSets,a);if(b.linkSets.splice(h,1),0==b.linkSets.length){var i=B.call(a.loader.loads,b);-1!=i&&a.loader.loads.splice(i,1)}}a.reject(c)}function m(a,b){if(a.loaderObj.trace){a.loaderObj.loads||(a.loaderObj.loads={});var c={};b.dependencies.forEach(function(a){c[a.key]=a.value}),a.loaderObj.loads[b.name]={name:b.name,deps:b.dependencies.map(function(a){return a.key}),depMap:c,address:b.address,metadata:b.metadata,source:b.source,kind:b.isDeclarative?"declarative":"dynamic"}}b.name&&(a.modules[b.name]=b.module);var d=B.call(a.loads,b);-1!=d&&a.loads.splice(d,1);for(var e=0,f=b.linkSets.length;f>e;e++)d=B.call(b.linkSets[e].loads,b),-1!=d&&b.linkSets[e].loads.splice(d,1);b.linkSets.splice(0,b.linkSets.length)}function n(a,b,c){if(c[a.groupIndex]=c[a.groupIndex]||[],-1==B.call(c[a.groupIndex],a)){c[a.groupIndex].push(a);for(var d=0,e=b.length;e>d;d++)for(var f=b[d],g=0;g=0;g--){for(var h=d[g],i=0;ic;c++){var g=d.importers[c];if(!g.locked){var h=B.call(g.dependencies,d);g.setters[h](e)}}return d.locked=!1,b});d.setters=f.setters,d.execute=f.execute;for(var g=0,h=a.dependencies.length;h>g;g++){var i=a.dependencies[g].value,j=c.modules[i];if(!j)for(var k=0;kf;f++){var h=e[f];if(h&&-1==B.call(b,h)&&(d=v(h,b,c)))return d=w(d,"Error evaluating "+h.name+"\n")}if(a.failed)return new Error("Module failed execution.");if(!a.evaluated)return a.evaluated=!0,d=t(a),d?a.failed=!0:Object.preventExtensions&&Object.preventExtensions(a.module),a.execute=void 0,d}}function w(a,b){return a instanceof Error?a.message=b+a.message:a=b+a,a}function x(a){if("object"!=typeof a)throw new TypeError("Options must be an object");a.normalize&&(this.normalize=a.normalize),a.locate&&(this.locate=a.locate),a.fetch&&(this.fetch=a.fetch),a.translate&&(this.translate=a.translate),a.instantiate&&(this.instantiate=a.instantiate),this._loader={loaderObj:this,loads:[],modules:{},importPromises:{},moduleRecords:{}},C(this,"global",{get:function(){return __global}}),this.traceurOptions={}}function y(){}function z(a,b,c){var d=a._loader.importPromises;return d[b]=c.then(function(a){return d[b]=void 0,a},function(a){throw d[b]=void 0,a})}var A=__global.Promise||require("when/es6-shim/Promise");__global.console&&(console.assert=console.assert||function(){});var B=Array.prototype.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},C=$__Object$defineProperty,D=0;x.prototype={constructor:x,define:function(a,b,c){if(this._loader.importPromises[a])throw new TypeError("Module is already loading.");return z(this,a,new A(g({step:"translate",loader:this._loader,moduleName:a,moduleMetadata:c&&c.metadata||{},moduleSource:b,moduleAddress:c&&c.address})))},"delete":function(a){return this._loader.modules[a]?delete this._loader.modules[a]:!1},get:function(a){return this._loader.modules[a]?(u(this._loader.modules[a],[],this),this._loader.modules[a].module):void 0},has:function(a){return!!this._loader.modules[a]},"import":function(a,c){var d=this;return A.resolve(d.normalize(a,c&&c.name,c&&c.address)).then(function(a){var e=d._loader;return e.modules[a]?(u(e.modules[a],[],e._loader),e.modules[a].module):e.importPromises[a]||z(d,a,b(e,a,c||{}).then(function(b){return delete e.importPromises[a],s(e,b)}))})},load:function(a){return this._loader.modules[a]?(u(this._loader.modules[a],[],this._loader),A.resolve(this._loader.modules[a].module)):this._loader.importPromises[a]||z(this,a,b(this._loader,a,{}))},module:function(b,c){var d=a();d.address=c&&c.address;var e=h(this._loader,d),g=A.resolve(b),i=this._loader,j=e.done.then(function(){return s(i,d)});return f(i,d,g),j},newModule:function(a){if("object"!=typeof a)throw new TypeError("Expected object");var b=new y;for(var c in a)!function(c){C(b,c,{configurable:!1,enumerable:!0,get:function(){return a[c]}})}(c);return Object.preventExtensions&&Object.preventExtensions(b),b},set:function(a,b){if(!(b instanceof y))throw new TypeError("Loader.set("+a+", module) must be a module");this._loader.modules[a]={module:b}},normalize:function(a){return a},locate:function(a){return a.name},fetch:function(){throw new TypeError("Fetch not implemented")},translate:function(a){return a.source},parse:function(){throw new TypeError("Loader.parse is not implemented")},instantiate:function(){}};var E=x.prototype.newModule;!function(){function a(a,b,c){try{return b.compile(a,c)}catch(d){throw d[0]}}var b;x.prototype.parse=function(c){if(!b)if("undefined"==typeof window&&"undefined"==typeof WorkerGlobalScope)b=require("traceur");else{if(!__global.traceur)throw new TypeError("Include Traceur for module syntax support");b=__global.traceur}c.isDeclarative=!0;var d=this.traceurOptions||{};d.modules="instantiate",d.script=!1,d.sourceMaps="inline",d.filename=c.address;var e=new b.Compiler(d),f=a(c.source,e,d.filename);if(!f)throw new Error("Error evaluating module "+c.address);var g=e.getSourceMap();__global.btoa&&g&&(f+="!eval"),f='var __moduleAddress = "'+c.address+'";'+f,__eval(f,__global,c)}}(),"object"==typeof exports&&(module.exports=x),__global.Reflect=__global.Reflect||{},__global.Reflect.Loader=__global.Reflect.Loader||x,__global.Reflect.global=__global.Reflect.global||__global,__global.LoaderPolyfill=x}(),function(){function a(a){var b=String(a).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@\/?#]*(?::[^:@\/?#]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);return b?{href:b[0]||"",protocol:b[1]||"",authority:b[2]||"",host:b[3]||"",hostname:b[4]||"",port:b[5]||"",pathname:b[6]||"",search:b[7]||"",hash:b[8]||""}:null}function b(a){var b=[];return a.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(a){"/.."===a?b.pop():b.push(a)}),b.join("").replace(/^\//,"/"===a.charAt(0)?"/":"")}function c(c,d){return d=a(d||""),c=a(c||""),d&&c?(d.protocol||c.protocol)+(d.protocol||d.authority?d.authority:c.authority)+b(d.protocol||d.authority||"/"===d.pathname.charAt(0)?d.pathname:d.pathname?(c.authority&&!c.pathname?"/":"")+c.pathname.slice(0,c.pathname.lastIndexOf("/")+1)+d.pathname:c.pathname)+(d.protocol||d.authority||d.pathname?d.search:d.search||c.search)+d.hash:null}function d(){document.removeEventListener("DOMContentLoaded",d,!1),window.removeEventListener("load",d,!1),e()}function e(){for(var a=document.getElementsByTagName("script"),b=0;b2)throw new TypeError("Only one wildcard in a path is permitted");if(1==g.length){if(d==f&&f.length>e.length){e=f;break}}else d.substr(0,g[0].length)==g[0]&&d.substr(d.length-g[1].length)==g[1]&&(e=f,b=d.substr(g[0].length,d.length-g[1].length-g[0].length))}var i=this.paths[e];return b&&(i=i.replace("*",b)),h&&(i=i.replace(/#/g,"%23")),c(this.baseURL,i)},enumerable:!1,writable:!0}),$__Object$defineProperty(b.prototype,"fetch",{value:function(a){var b=this;return new j(function(d,e){f(c(b.baseURL,a.address),function(a){d(a)},e)})},enumerable:!1,writable:!0}),b}(__global.LoaderPolyfill),m=new l;if("object"==typeof exports&&(module.exports=m),__global.System=m,h&&"undefined"!=typeof document.getElementsByTagName){var n=document.getElementsByTagName("script");n=n[n.length-1],"complete"===document.readyState?setTimeout(e):document.addEventListener&&(document.addEventListener("DOMContentLoaded",d,!1),window.addEventListener("load",d,!1)),n.getAttribute("data-init")&&window[n.getAttribute("data-init")]()}}()}("undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope?self:global);
+//# sourceMappingURL=es6-module-loader.js.map
\ No newline at end of file
diff --git a/jspm_packages/es6-module-loader.js.map b/jspm_packages/es6-module-loader.js.map
new file mode 100644
index 0000000..078f9a2
--- /dev/null
+++ b/jspm_packages/es6-module-loader.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"es6-module-loader.js","sources":["es6-module-loader.src.js"],"names":["e","exports","module","define","amd","window","Promise","global","self","t","n","r","s","o","u","a","require","i","Error","f","call","length",1,"unhandledRejections","PromiseConstructor","../lib/Promise","../lib/decorators/unhandledRejection",2,"makePromise","Scheduler","async","asap","scheduler","factory","./Scheduler","./env","./makePromise",3,"this","_async","_running","_queue","Array","_queueLen","_afterQueue","_afterQueueLen","drain","_drain","prototype","enqueue","task","run","afterQueue",4,"throwit","noop","setTimer","format","report","handled","reported","push","logError","id","formatError","value","unreport","indexOf","splice","logInfo","formatObject","x","tasks","running","flush","shift","localConsole","console","error","log","info","onPotentiallyUnhandledRejection","rejection","onPotentiallyUnhandledRejectionHandled","onFatalRejection","../env","../format",5,"isNode","process","nextTick","hasMutationObserver","MutationObserver","WebKitMutationObserver","initMutationObserver","scheduled","node","document","createTextNode","observe","characterData","data","MutationObs","capturedSetTimeout","setTimeout","ms","clearTimer","clearTimeout","vertxRequire","vertx","cancelTimer","runOnLoop","runOnContext",6,"stack","String","JSON","tryStringify","defaultValue","stringify",7,"environment","resolver","handler","_handler","Handler","init","promiseResolve","resolve","promiseReject","reason","reject","promiseNotify","notify","Pending","isPromise","Async","getHandler","Rejected","never","foreverPendingPromise","defer","begetFrom","parent","child","receiver","join","context","all","promises","traverseWith","snd","traverse","tryCatch2","tryMap","mapAt","resolved","traverseAt","settleAt","results","pending","become","Fulfilled","maybeThenable","h","getHandlerMaybeThenable","state","fold","visitRemaining","start","markAsHandled","visit","_unreport","race","TypeError","runRace","getHandlerUntrusted","untrustedThen","then","Thenable","FailIfRejected","inheritedContext","createContext","consumers","thenable","AssimilateTask","errorId","_report","ReportTask","UnreportTask","cycle","ContinuationTask","continuation","ProgressTask","_then","tryAssimilate","Fold","z","c","to","failIfRejected","runContinuation1","next","enterContext","tryCatchReject","exitContext","runContinuation3","tryCatchReject3","runNotify","tryCatchReturn","b","thisArg","y","inherit","Parent","Child","objectCreate","constructor","Object","create","proto","_defer","onFulfilled","onRejected","onProgress","p","_beget","chain","_traverse","_visitRemaining","when","fail","_state","fulfilled","rejected","progress","q","cont","foreverPendingHandler","_resolve","_reject","_notify","__global","__eval","__source","load","__curRegister","System","register","name","deps","declare","depsList","eval","replace","message","address","$__Object$getPrototypeOf","getPrototypeOf","obj","__proto__","$__Object$defineProperty","defineProperty","prop","opt","get","$__Object$create","props","F","hasOwnProperty","createLoad","status","linkSets","dependencies","metadata","loadModule","loader","options","asyncStartLoadPartwayThrough","step","moduleName","moduleMetadata","moduleSource","source","moduleAddress","requestLoad","request","refererName","refererAddress","loaderObj","normalize","modules","l","loads","proceedToLocate","proceedToFetch","locate","proceedToTranslate","fetch","translate","instantiate","instantiateResult","undefined","anonCnt","isDeclarative","parse","execute","loadPromises","index","depLoad","key","concat","addLoadToLinkSet","updateLinkSetOnLoad","exc","exception","linkSetFailed","stepState","existingLoad","done","linkSet","createLinkSet","startingLoad","loadingCount","j","d","doLink","link","_newModule","evaluated","finishLoad","abrupt","addToError","failed","linkIndex","globalLoadsIndex","trace","depMap","forEach","dep","map","kind","loadIndex","buildLinkageGroups","groups","groupIndex","loadDep","loadDepGroupIndex","doDynamicExecute","linkError","Module","curGroupDeclarative","group","linkDeclarativeModule","getOrCreateModuleRecord","moduleRecords","importers","moduleObj","registryEntry","locked","importerModule","importerIndex","setters","depName","depModule","evaluateLoadedModule","doEnsureEvaluated","doExecute","seen","err","ensureEvaluated","preventExtensions","msg","Loader","_loader","importPromises","traceurOptions","createImportPromise","promise","m","assert","item","thisLen","delete","has","import","sourcePromise","newModule","configurable","enumerable","set","doCompile","compiler","filename","compile","traceur","WorkerGlobalScope","script","sourceMaps","Compiler","sourceMap","getSourceMap","btoa","Reflect","LoaderPolyfill","parseURI","url","match","href","protocol","authority","host","hostname","port","pathname","search","hash","removeDotSegments","input","output","pop","charAt","toAbsoluteURL","base","slice","lastIndexOf","completed","removeEventListener","ready","scripts","getElementsByTagName","type","innerHTML","substr","fetchTextFromURL","isWorker","isBrowser","isWindows","platform","XMLHttpRequest","fulfill","xhr","responseText","statusText","sameDomain","doTimeout","domainCheck","exec","location","XDomainRequest","onload","onerror","ontimeout","onprogress","timeout","onreadystatechange","readyState","open","send","fs","readFile","SystemLoader","$__super","split","baseURL","substring","cwd","paths","*","Function","parentName","segments","rel","dotdots","segment","normalizedParts","parentParts","writable","w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W,GACzDra,OAAO8d,iBAAiB,OAAQzD,GAAW,IAIzCwD,EAAUE,aAAa,cACzB/d,OAAO6d,EAAUE,aAAa,qBAgChB,mBAAV/d,QAAwBA,OAAsC,mBAArBuY,mBACRpY,KAAOD"}
\ No newline at end of file
diff --git a/jspm_packages/es6-module-loader.src.js b/jspm_packages/es6-module-loader.src.js
new file mode 100644
index 0000000..f9ec463
--- /dev/null
+++ b/jspm_packages/es6-module-loader.src.js
@@ -0,0 +1,2770 @@
+!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.Promise=e():"undefined"!=typeof global?global.Promise=e():"undefined"!=typeof self&&(self.Promise=e())}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= 0) {
+ reported.splice(i, 1);
+ logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
+ }
+ }
+
+ function enqueue(f, x) {
+ tasks.push(f, x);
+ if(running === null) {
+ running = setTimer(flush, 0);
+ }
+ }
+
+ function flush() {
+ running = null;
+ while(tasks.length > 0) {
+ tasks.shift()(tasks.shift());
+ }
+ }
+
+ return Promise;
+ };
+
+ function throwit(e) {
+ throw e;
+ }
+
+ function noop() {}
+
+});
+}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
+
+},{"../env":5,"../format":6}],5:[function(require,module,exports){
+/** @license MIT License (c) copyright 2010-2014 original author or authors */
+/** @author Brian Cavalier */
+/** @author John Hann */
+
+/*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
+(function(define) { 'use strict';
+define(function(require) {
+ /*jshint maxcomplexity:6*/
+
+ // Sniff "best" async scheduling option
+ // Prefer process.nextTick or MutationObserver, then check for
+ // setTimeout, and finally vertx, since its the only env that doesn't
+ // have setTimeout
+
+ var MutationObs;
+ var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
+
+ // Default env
+ var setTimer = function(f, ms) { return setTimeout(f, ms); };
+ var clearTimer = function(t) { return clearTimeout(t); };
+ var asap = function (f) { return capturedSetTimeout(f, 0); };
+
+ // Detect specific env
+ if (isNode()) { // Node
+ asap = function (f) { return process.nextTick(f); };
+
+ } else if (MutationObs = hasMutationObserver()) { // Modern browser
+ asap = initMutationObserver(MutationObs);
+
+ } else if (!capturedSetTimeout) { // vert.x
+ var vertxRequire = require;
+ var vertx = vertxRequire('vertx');
+ setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
+ clearTimer = vertx.cancelTimer;
+ asap = vertx.runOnLoop || vertx.runOnContext;
+ }
+
+ return {
+ setTimer: setTimer,
+ clearTimer: clearTimer,
+ asap: asap
+ };
+
+ function isNode () {
+ return typeof process !== 'undefined' && process !== null &&
+ typeof process.nextTick === 'function';
+ }
+
+ function hasMutationObserver () {
+ return (typeof MutationObserver === 'function' && MutationObserver) ||
+ (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver);
+ }
+
+ function initMutationObserver(MutationObserver) {
+ var scheduled;
+ var node = document.createTextNode('');
+ var o = new MutationObserver(run);
+ o.observe(node, { characterData: true });
+
+ function run() {
+ var f = scheduled;
+ scheduled = void 0;
+ f();
+ }
+
+ var i = 0;
+ return function (f) {
+ scheduled = f;
+ node.data = (i ^= 1);
+ };
+ }
+});
+}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
+
+},{}],6:[function(require,module,exports){
+/** @license MIT License (c) copyright 2010-2014 original author or authors */
+/** @author Brian Cavalier */
+/** @author John Hann */
+
+(function(define) { 'use strict';
+define(function() {
+
+ return {
+ formatError: formatError,
+ formatObject: formatObject,
+ tryStringify: tryStringify
+ };
+
+ /**
+ * Format an error into a string. If e is an Error and has a stack property,
+ * it's returned. Otherwise, e is formatted using formatObject, with a
+ * warning added about e not being a proper Error.
+ * @param {*} e
+ * @returns {String} formatted string, suitable for output to developers
+ */
+ function formatError(e) {
+ var s = typeof e === 'object' && e !== null && e.stack ? e.stack : formatObject(e);
+ return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
+ }
+
+ /**
+ * Format an object, detecting "plain" objects and running them through
+ * JSON.stringify if possible.
+ * @param {Object} o
+ * @returns {string}
+ */
+ function formatObject(o) {
+ var s = String(o);
+ if(s === '[object Object]' && typeof JSON !== 'undefined') {
+ s = tryStringify(o, s);
+ }
+ return s;
+ }
+
+ /**
+ * Try to return the result of JSON.stringify(x). If that fails, return
+ * defaultValue
+ * @param {*} x
+ * @param {*} defaultValue
+ * @returns {String|*} JSON.stringify(x) or defaultValue
+ */
+ function tryStringify(x, defaultValue) {
+ try {
+ return JSON.stringify(x);
+ } catch(e) {
+ return defaultValue;
+ }
+ }
+
+});
+}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
+
+},{}],7:[function(require,module,exports){
+/** @license MIT License (c) copyright 2010-2014 original author or authors */
+/** @author Brian Cavalier */
+/** @author John Hann */
+
+(function(define) { 'use strict';
+define(function() {
+
+ return function makePromise(environment) {
+
+ var tasks = environment.scheduler;
+
+ var objectCreate = Object.create ||
+ function(proto) {
+ function Child() {}
+ Child.prototype = proto;
+ return new Child();
+ };
+
+ /**
+ * Create a promise whose fate is determined by resolver
+ * @constructor
+ * @returns {Promise} promise
+ * @name Promise
+ */
+ function Promise(resolver, handler) {
+ this._handler = resolver === Handler ? handler : init(resolver);
+ }
+
+ /**
+ * Run the supplied resolver
+ * @param resolver
+ * @returns {Pending}
+ */
+ function init(resolver) {
+ var handler = new Pending();
+
+ try {
+ resolver(promiseResolve, promiseReject, promiseNotify);
+ } catch (e) {
+ promiseReject(e);
+ }
+
+ return handler;
+
+ /**
+ * Transition from pre-resolution state to post-resolution state, notifying
+ * all listeners of the ultimate fulfillment or rejection
+ * @param {*} x resolution value
+ */
+ function promiseResolve (x) {
+ handler.resolve(x);
+ }
+ /**
+ * Reject this promise with reason, which will be used verbatim
+ * @param {Error|*} reason rejection reason, strongly suggested
+ * to be an Error type
+ */
+ function promiseReject (reason) {
+ handler.reject(reason);
+ }
+
+ /**
+ * @deprecated
+ * Issue a progress event, notifying all progress listeners
+ * @param {*} x progress event payload to pass to all listeners
+ */
+ function promiseNotify (x) {
+ handler.notify(x);
+ }
+ }
+
+ // Creation
+
+ Promise.resolve = resolve;
+ Promise.reject = reject;
+ Promise.never = never;
+
+ Promise._defer = defer;
+ Promise._handler = getHandler;
+
+ /**
+ * Returns a trusted promise. If x is already a trusted promise, it is
+ * returned, otherwise returns a new trusted Promise which follows x.
+ * @param {*} x
+ * @return {Promise} promise
+ */
+ function resolve(x) {
+ return isPromise(x) ? x
+ : new Promise(Handler, new Async(getHandler(x)));
+ }
+
+ /**
+ * Return a reject promise with x as its reason (x is used verbatim)
+ * @param {*} x
+ * @returns {Promise} rejected promise
+ */
+ function reject(x) {
+ return new Promise(Handler, new Async(new Rejected(x)));
+ }
+
+ /**
+ * Return a promise that remains pending forever
+ * @returns {Promise} forever-pending promise.
+ */
+ function never() {
+ return foreverPendingPromise; // Should be frozen
+ }
+
+ /**
+ * Creates an internal {promise, resolver} pair
+ * @private
+ * @returns {Promise}
+ */
+ function defer() {
+ return new Promise(Handler, new Pending());
+ }
+
+ // Transformation and flow control
+
+ /**
+ * Transform this promise's fulfillment value, returning a new Promise
+ * for the transformed result. If the promise cannot be fulfilled, onRejected
+ * is called with the reason. onProgress *may* be called with updates toward
+ * this promise's fulfillment.
+ * @param {function=} onFulfilled fulfillment handler
+ * @param {function=} onRejected rejection handler
+ * @param {function=} onProgress @deprecated progress handler
+ * @return {Promise} new promise
+ */
+ Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
+ var parent = this._handler;
+ var state = parent.join().state();
+
+ if ((typeof onFulfilled !== 'function' && state > 0) ||
+ (typeof onRejected !== 'function' && state < 0)) {
+ // Short circuit: value will not change, simply share handler
+ return new this.constructor(Handler, parent);
+ }
+
+ var p = this._beget();
+ var child = p._handler;
+
+ parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
+
+ return p;
+ };
+
+ /**
+ * If this promise cannot be fulfilled due to an error, call onRejected to
+ * handle the error. Shortcut for .then(undefined, onRejected)
+ * @param {function?} onRejected
+ * @return {Promise}
+ */
+ Promise.prototype['catch'] = function(onRejected) {
+ return this.then(void 0, onRejected);
+ };
+
+ /**
+ * Creates a new, pending promise of the same type as this promise
+ * @private
+ * @returns {Promise}
+ */
+ Promise.prototype._beget = function() {
+ return begetFrom(this._handler, this.constructor);
+ };
+
+ function begetFrom(parent, Promise) {
+ var child = new Pending(parent.receiver, parent.join().context);
+ return new Promise(Handler, child);
+ }
+
+ // Array combinators
+
+ Promise.all = all;
+ Promise.race = race;
+ Promise._traverse = traverse;
+
+ /**
+ * Return a promise that will fulfill when all promises in the
+ * input array have fulfilled, or will reject when one of the
+ * promises rejects.
+ * @param {array} promises array of promises
+ * @returns {Promise} promise for array of fulfillment values
+ */
+ function all(promises) {
+ return traverseWith(snd, null, promises);
+ }
+
+ /**
+ * Array> -> Promise>
+ * @private
+ * @param {function} f function to apply to each promise's value
+ * @param {Array} promises array of promises
+ * @returns {Promise} promise for transformed values
+ */
+ function traverse(f, promises) {
+ return traverseWith(tryCatch2, f, promises);
+ }
+
+ function traverseWith(tryMap, f, promises) {
+ var handler = typeof f === 'function' ? mapAt : settleAt;
+
+ var resolver = new Pending();
+ var pending = promises.length >>> 0;
+ var results = new Array(pending);
+
+ for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
+ x = promises[i];
+
+ if (x === void 0 && !(i in promises)) {
+ --pending;
+ continue;
+ }
+
+ traverseAt(promises, handler, i, x, resolver);
+ }
+
+ if(pending === 0) {
+ resolver.become(new Fulfilled(results));
+ }
+
+ return new Promise(Handler, resolver);
+
+ function mapAt(i, x, resolver) {
+ if(!resolver.resolved) {
+ traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
+ }
+ }
+
+ function settleAt(i, x, resolver) {
+ results[i] = x;
+ if(--pending === 0) {
+ resolver.become(new Fulfilled(results));
+ }
+ }
+ }
+
+ function traverseAt(promises, handler, i, x, resolver) {
+ if (maybeThenable(x)) {
+ var h = getHandlerMaybeThenable(x);
+ var s = h.state();
+
+ if (s === 0) {
+ h.fold(handler, i, void 0, resolver);
+ } else if (s > 0) {
+ handler(i, h.value, resolver);
+ } else {
+ resolver.become(h);
+ visitRemaining(promises, i+1, h);
+ }
+ } else {
+ handler(i, x, resolver);
+ }
+ }
+
+ Promise._visitRemaining = visitRemaining;
+ function visitRemaining(promises, start, handler) {
+ for(var i=start; i load contains linkSet');
+
+ if (load.linkSets.indexOf(linkSet) != -1)
+ console.assert(linkSet.loads.indexOf(load) != -1, 'load contains linkSet -> linkSet contains load');
+ }
+ }
+
+ for (var i = 0; i < linkSets.length; i++) {
+ var linkSet = linkSets[i];
+ for (var j = 0; j < linkSet.loads.length; j++) {
+ var load = linkSet.loads[j];
+
+ for (var k = 0; k < load.dependencies.length; k++) {
+ var depName = load.dependencies[k].value;
+ var depLoad;
+ for (var l = 0; l < loads.length; l++) {
+ if (loads[l].name != depName)
+ continue;
+ depLoad = loads[l];
+ break;
+ }
+
+ // loading records are allowed not to have their dependencies yet
+ // if (load.status != 'loading')
+ // console.assert(depLoad, 'depLoad found');
+
+ // console.assert(linkSet.loads.indexOf(depLoad) != -1, 'linkset contains all dependencies');
+ }
+ }
+ }
+} */
+
+
+(function() {
+ var Promise = __global.Promise || require('when/es6-shim/Promise');
+ if (__global.console)
+ console.assert = console.assert || function() {};
+
+ // IE8 support
+ var indexOf = Array.prototype.indexOf || function(item) {
+ for (var i = 0, thisLen = this.length; i < thisLen; i++) {
+ if (this[i] === item) {
+ return i;
+ }
+ }
+ return -1;
+ };
+ var defineProperty = $__Object$defineProperty;
+
+ // 15.2.3 - Runtime Semantics: Loader State
+
+ // 15.2.3.11
+ function createLoaderLoad(object) {
+ return {
+ // modules is an object for ES5 implementation
+ modules: {},
+ loads: [],
+ loaderObj: object
+ };
+ }
+
+ // 15.2.3.2 Load Records and LoadRequest Objects
+
+ // 15.2.3.2.1
+ function createLoad(name) {
+ return {
+ status: 'loading',
+ name: name,
+ linkSets: [],
+ dependencies: [],
+ metadata: {}
+ };
+ }
+
+ // 15.2.3.2.2 createLoadRequestObject, absorbed into calling functions
+
+ // 15.2.4
+
+ // 15.2.4.1
+ function loadModule(loader, name, options) {
+ return new Promise(asyncStartLoadPartwayThrough({
+ step: options.address ? 'fetch' : 'locate',
+ loader: loader,
+ moduleName: name,
+ // allow metadata for import https://bugs.ecmascript.org/show_bug.cgi?id=3091
+ moduleMetadata: options && options.metadata || {},
+ moduleSource: options.source,
+ moduleAddress: options.address
+ }));
+ }
+
+ // 15.2.4.2
+ function requestLoad(loader, request, refererName, refererAddress) {
+ // 15.2.4.2.1 CallNormalize
+ return new Promise(function(resolve, reject) {
+ resolve(loader.loaderObj.normalize(request, refererName, refererAddress));
+ })
+ // 15.2.4.2.2 GetOrCreateLoad
+ .then(function(name) {
+ var load;
+ if (loader.modules[name]) {
+ load = createLoad(name);
+ load.status = 'linked';
+ // https://bugs.ecmascript.org/show_bug.cgi?id=2795
+ load.module = loader.modules[name];
+ return load;
+ }
+
+ for (var i = 0, l = loader.loads.length; i < l; i++) {
+ load = loader.loads[i];
+ if (load.name != name)
+ continue;
+ console.assert(load.status == 'loading' || load.status == 'loaded', 'loading or loaded');
+ return load;
+ }
+
+ load = createLoad(name);
+ loader.loads.push(load);
+
+ proceedToLocate(loader, load);
+
+ return load;
+ });
+ }
+
+ // 15.2.4.3
+ function proceedToLocate(loader, load) {
+ proceedToFetch(loader, load,
+ Promise.resolve()
+ // 15.2.4.3.1 CallLocate
+ .then(function() {
+ return loader.loaderObj.locate({ name: load.name, metadata: load.metadata });
+ })
+ );
+ }
+
+ // 15.2.4.4
+ function proceedToFetch(loader, load, p) {
+ proceedToTranslate(loader, load,
+ p
+ // 15.2.4.4.1 CallFetch
+ .then(function(address) {
+ // adjusted, see https://bugs.ecmascript.org/show_bug.cgi?id=2602
+ if (load.status != 'loading')
+ return;
+ load.address = address;
+
+ return loader.loaderObj.fetch({ name: load.name, metadata: load.metadata, address: address });
+ })
+ );
+ }
+
+ var anonCnt = 0;
+
+ // 15.2.4.5
+ function proceedToTranslate(loader, load, p) {
+ p
+ // 15.2.4.5.1 CallTranslate
+ .then(function(source) {
+ if (load.status != 'loading')
+ return;
+ return loader.loaderObj.translate({ name: load.name, metadata: load.metadata, address: load.address, source: source });
+ })
+
+ // 15.2.4.5.2 CallInstantiate
+ .then(function(source) {
+ if (load.status != 'loading')
+ return;
+ load.source = source;
+ return loader.loaderObj.instantiate({ name: load.name, metadata: load.metadata, address: load.address, source: source });
+ })
+
+ // 15.2.4.5.3 InstantiateSucceeded
+ .then(function(instantiateResult) {
+ if (load.status != 'loading')
+ return;
+
+ if (instantiateResult === undefined) {
+ load.address = load.address || '';
+
+ // instead of load.kind, use load.isDeclarative
+ load.isDeclarative = true;
+ // parse sets load.declare, load.depsList
+ loader.loaderObj.parse(load);
+ }
+ else if (typeof instantiateResult == 'object') {
+ load.depsList = instantiateResult.deps || [];
+ load.execute = instantiateResult.execute;
+ load.isDeclarative = false;
+ }
+ else
+ throw TypeError('Invalid instantiate return value');
+
+ // 15.2.4.6 ProcessLoadDependencies
+ load.dependencies = [];
+ var depsList = load.depsList;
+
+ var loadPromises = [];
+ for (var i = 0, l = depsList.length; i < l; i++) (function(request, index) {
+ loadPromises.push(
+ requestLoad(loader, request, load.name, load.address)
+
+ // 15.2.4.6.1 AddDependencyLoad (load is parentLoad)
+ .then(function(depLoad) {
+
+ console.assert(!load.dependencies.some(function(dep) {
+ return dep.key == request;
+ }), 'not already a dependency');
+
+ // adjusted from spec to maintain dependency order
+ // this is due to the System.register internal implementation needs
+ load.dependencies[index] = {
+ key: request,
+ value: depLoad.name
+ };
+
+ if (depLoad.status != 'linked') {
+ var linkSets = load.linkSets.concat([]);
+ for (var i = 0, l = linkSets.length; i < l; i++)
+ addLoadToLinkSet(linkSets[i], depLoad);
+ }
+
+ // console.log('AddDependencyLoad ' + depLoad.name + ' for ' + load.name);
+ // snapshot(loader);
+ })
+ );
+ })(depsList[i], i);
+
+ return Promise.all(loadPromises);
+ })
+
+ // 15.2.4.6.2 LoadSucceeded
+ .then(function() {
+ // console.log('LoadSucceeded ' + load.name);
+ // snapshot(loader);
+
+ console.assert(load.status == 'loading', 'is loading');
+
+ load.status = 'loaded';
+
+ var linkSets = load.linkSets.concat([]);
+ for (var i = 0, l = linkSets.length; i < l; i++)
+ updateLinkSetOnLoad(linkSets[i], load);
+ })
+
+ // 15.2.4.5.4 LoadFailed
+ ['catch'](function(exc) {
+ console.assert(load.status == 'loading', 'is loading on fail');
+ load.status = 'failed';
+ load.exception = exc;
+
+ var linkSets = load.linkSets.concat([]);
+ for (var i = 0, l = linkSets.length; i < l; i++) {
+ linkSetFailed(linkSets[i], load, exc);
+ }
+
+ console.assert(load.linkSets.length == 0, 'linkSets not removed');
+ });
+ }
+
+ // 15.2.4.7 PromiseOfStartLoadPartwayThrough absorbed into calling functions
+
+ // 15.2.4.7.1
+ function asyncStartLoadPartwayThrough(stepState) {
+ return function(resolve, reject) {
+ var loader = stepState.loader;
+ var name = stepState.moduleName;
+ var step = stepState.step;
+
+ if (loader.modules[name])
+ throw new TypeError('"' + name + '" already exists in the module table');
+
+ // adjusted to pick up existing loads
+ var existingLoad;
+ for (var i = 0, l = loader.loads.length; i < l; i++) {
+ if (loader.loads[i].name == name) {
+ existingLoad = loader.loads[i];
+ return existingLoad.linkSets[0].done.then(function() {
+ resolve(existingLoad);
+ });
+ }
+ }
+
+ var load = createLoad(name);
+
+ load.metadata = stepState.moduleMetadata;
+
+ var linkSet = createLinkSet(loader, load);
+
+ loader.loads.push(load);
+
+ resolve(linkSet.done);
+
+ if (step == 'locate')
+ proceedToLocate(loader, load);
+
+ else if (step == 'fetch')
+ proceedToFetch(loader, load, Promise.resolve(stepState.moduleAddress));
+
+ else {
+ console.assert(step == 'translate', 'translate step');
+ load.address = stepState.moduleAddress;
+ proceedToTranslate(loader, load, Promise.resolve(stepState.moduleSource));
+ }
+ }
+ }
+
+ // Declarative linking functions run through alternative implementation:
+ // 15.2.5.1.1 CreateModuleLinkageRecord not implemented
+ // 15.2.5.1.2 LookupExport not implemented
+ // 15.2.5.1.3 LookupModuleDependency not implemented
+
+ // 15.2.5.2.1
+ function createLinkSet(loader, startingLoad) {
+ var linkSet = {
+ loader: loader,
+ loads: [],
+ startingLoad: startingLoad, // added see spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995
+ loadingCount: 0
+ };
+ linkSet.done = new Promise(function(resolve, reject) {
+ linkSet.resolve = resolve;
+ linkSet.reject = reject;
+ });
+ addLoadToLinkSet(linkSet, startingLoad);
+ return linkSet;
+ }
+ // 15.2.5.2.2
+ function addLoadToLinkSet(linkSet, load) {
+ console.assert(load.status == 'loading' || load.status == 'loaded', 'loading or loaded on link set');
+
+ for (var i = 0, l = linkSet.loads.length; i < l; i++)
+ if (linkSet.loads[i] == load)
+ return;
+
+ linkSet.loads.push(load);
+ load.linkSets.push(linkSet);
+
+ // adjustment, see https://bugs.ecmascript.org/show_bug.cgi?id=2603
+ if (load.status != 'loaded') {
+ linkSet.loadingCount++;
+ }
+
+ var loader = linkSet.loader;
+
+ for (var i = 0, l = load.dependencies.length; i < l; i++) {
+ var name = load.dependencies[i].value;
+
+ if (loader.modules[name])
+ continue;
+
+ for (var j = 0, d = loader.loads.length; j < d; j++) {
+ if (loader.loads[j].name != name)
+ continue;
+
+ addLoadToLinkSet(linkSet, loader.loads[j]);
+ break;
+ }
+ }
+ // console.log('add to linkset ' + load.name);
+ // snapshot(linkSet.loader);
+ }
+
+ // linking errors can be generic or load-specific
+ // this is necessary for debugging info
+ function doLink(linkSet) {
+ var error = false;
+ try {
+ link(linkSet, function(load, exc) {
+ linkSetFailed(linkSet, load, exc);
+ error = true;
+ });
+ }
+ catch(e) {
+ linkSetFailed(linkSet, null, e);
+ error = true;
+ }
+ return error;
+ }
+
+ // 15.2.5.2.3
+ function updateLinkSetOnLoad(linkSet, load) {
+ // console.log('update linkset on load ' + load.name);
+ // snapshot(linkSet.loader);
+
+ console.assert(load.status == 'loaded' || load.status == 'linked', 'loaded or linked');
+
+ linkSet.loadingCount--;
+
+ if (linkSet.loadingCount > 0)
+ return;
+
+ // adjusted for spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995
+ var startingLoad = linkSet.startingLoad;
+
+ // non-executing link variation for loader tracing
+ // on the server. Not in spec.
+ /***/
+ if (linkSet.loader.loaderObj.execute === false) {
+ var loads = [].concat(linkSet.loads);
+ for (var i = 0, l = loads.length; i < l; i++) {
+ var load = loads[i];
+ load.module = !load.isDeclarative ? {
+ module: _newModule({})
+ } : {
+ name: load.name,
+ module: _newModule({}),
+ evaluated: true
+ };
+ load.status = 'linked';
+ finishLoad(linkSet.loader, load);
+ }
+ return linkSet.resolve(startingLoad);
+ }
+ /***/
+
+ var abrupt = doLink(linkSet);
+
+ if (abrupt)
+ return;
+
+ console.assert(linkSet.loads.length == 0, 'loads cleared');
+
+ linkSet.resolve(startingLoad);
+ }
+
+ // 15.2.5.2.4
+ function linkSetFailed(linkSet, load, exc) {
+ var loader = linkSet.loader;
+
+ if (linkSet.loads[0].name != load.name)
+ exc = addToError(exc, 'Error loading "' + load.name + '" from "' + linkSet.loads[0].name + '" at ' + (linkSet.loads[0].address || '') + '\n');
+
+ exc = addToError(exc, 'Error loading "' + load.name + '" at ' + (load.address || '') + '\n');
+
+ var loads = linkSet.loads.concat([]);
+ for (var i = 0, l = loads.length; i < l; i++) {
+ var load = loads[i];
+
+ // store all failed load records
+ loader.loaderObj.failed = loader.loaderObj.failed || [];
+ if (indexOf.call(loader.loaderObj.failed, load) == -1)
+ loader.loaderObj.failed.push(load);
+
+ var linkIndex = indexOf.call(load.linkSets, linkSet);
+ console.assert(linkIndex != -1, 'link not present');
+ load.linkSets.splice(linkIndex, 1);
+ if (load.linkSets.length == 0) {
+ var globalLoadsIndex = indexOf.call(linkSet.loader.loads, load);
+ if (globalLoadsIndex != -1)
+ linkSet.loader.loads.splice(globalLoadsIndex, 1);
+ }
+ }
+ linkSet.reject(exc);
+ }
+
+ // 15.2.5.2.5
+ function finishLoad(loader, load) {
+ // add to global trace if tracing
+ if (loader.loaderObj.trace) {
+ if (!loader.loaderObj.loads)
+ loader.loaderObj.loads = {};
+ var depMap = {};
+ load.dependencies.forEach(function(dep) {
+ depMap[dep.key] = dep.value;
+ });
+ loader.loaderObj.loads[load.name] = {
+ name: load.name,
+ deps: load.dependencies.map(function(dep){ return dep.key }),
+ depMap: depMap,
+ address: load.address,
+ metadata: load.metadata,
+ source: load.source,
+ kind: load.isDeclarative ? 'declarative' : 'dynamic'
+ };
+ }
+ // if not anonymous, add to the module table
+ if (load.name) {
+ console.assert(!loader.modules[load.name], 'load not in module table');
+ loader.modules[load.name] = load.module;
+ }
+ var loadIndex = indexOf.call(loader.loads, load);
+ if (loadIndex != -1)
+ loader.loads.splice(loadIndex, 1);
+ for (var i = 0, l = load.linkSets.length; i < l; i++) {
+ loadIndex = indexOf.call(load.linkSets[i].loads, load);
+ if (loadIndex != -1)
+ load.linkSets[i].loads.splice(loadIndex, 1);
+ }
+ load.linkSets.splice(0, load.linkSets.length);
+ }
+
+ // 15.2.5.3 Module Linking Groups
+
+ // 15.2.5.3.2 BuildLinkageGroups alternative implementation
+ // Adjustments (also see https://bugs.ecmascript.org/show_bug.cgi?id=2755)
+ // 1. groups is an already-interleaved array of group kinds
+ // 2. load.groupIndex is set when this function runs
+ // 3. load.groupIndex is the interleaved index ie 0 declarative, 1 dynamic, 2 declarative, ... (or starting with dynamic)
+ function buildLinkageGroups(load, loads, groups) {
+ groups[load.groupIndex] = groups[load.groupIndex] || [];
+
+ // if the load already has a group index and its in its group, its already been done
+ // this logic naturally handles cycles
+ if (indexOf.call(groups[load.groupIndex], load) != -1)
+ return;
+
+ // now add it to the group to indicate its been seen
+ groups[load.groupIndex].push(load);
+
+ for (var i = 0, l = loads.length; i < l; i++) {
+ var loadDep = loads[i];
+
+ // dependencies not found are already linked
+ for (var j = 0; j < load.dependencies.length; j++) {
+ if (loadDep.name == load.dependencies[j].value) {
+ // by definition all loads in linkset are loaded, not linked
+ console.assert(loadDep.status == 'loaded', 'Load in linkSet not loaded!');
+
+ // if it is a group transition, the index of the dependency has gone up
+ // otherwise it is the same as the parent
+ var loadDepGroupIndex = load.groupIndex + (loadDep.isDeclarative != load.isDeclarative);
+
+ // the group index of an entry is always the maximum
+ if (loadDep.groupIndex === undefined || loadDep.groupIndex < loadDepGroupIndex) {
+
+ // if already in a group, remove from the old group
+ if (loadDep.groupIndex !== undefined) {
+ groups[loadDep.groupIndex].splice(indexOf.call(groups[loadDep.groupIndex], loadDep), 1);
+
+ // if the old group is empty, then we have a mixed depndency cycle
+ if (groups[loadDep.groupIndex].length == 0)
+ throw new TypeError("Mixed dependency cycle detected");
+ }
+
+ loadDep.groupIndex = loadDepGroupIndex;
+ }
+
+ buildLinkageGroups(loadDep, loads, groups);
+ }
+ }
+ }
+ }
+
+ function doDynamicExecute(linkSet, load, linkError) {
+ try {
+ var module = load.execute();
+ }
+ catch(e) {
+ linkError(load, e);
+ return;
+ }
+ if (!module || !(module instanceof Module))
+ linkError(load, new TypeError('Execution must define a Module instance'));
+ else
+ return module;
+ }
+
+ // 15.2.5.4
+ function link(linkSet, linkError) {
+
+ var loader = linkSet.loader;
+
+ if (!linkSet.loads.length)
+ return;
+
+ // console.log('linking {' + logloads(linkSet.loads) + '}');
+ // snapshot(loader);
+
+ // 15.2.5.3.1 LinkageGroups alternative implementation
+
+ // build all the groups
+ // because the first load represents the top of the tree
+ // for a given linkset, we can work down from there
+ var groups = [];
+ var startingLoad = linkSet.loads[0];
+ startingLoad.groupIndex = 0;
+ buildLinkageGroups(startingLoad, linkSet.loads, groups);
+
+ // determine the kind of the bottom group
+ var curGroupDeclarative = startingLoad.isDeclarative == groups.length % 2;
+
+ // run through the groups from bottom to top
+ for (var i = groups.length - 1; i >= 0; i--) {
+ var group = groups[i];
+ for (var j = 0; j < group.length; j++) {
+ var load = group[j];
+
+ // 15.2.5.5 LinkDeclarativeModules adjusted
+ if (curGroupDeclarative) {
+ linkDeclarativeModule(load, linkSet.loads, loader);
+ }
+ // 15.2.5.6 LinkDynamicModules adjusted
+ else {
+ var module = doDynamicExecute(linkSet, load, linkError);
+ if (!module)
+ return;
+ load.module = {
+ name: load.name,
+ module: module
+ };
+ load.status = 'linked';
+ }
+ finishLoad(loader, load);
+ }
+
+ // alternative current kind for next loop
+ curGroupDeclarative = !curGroupDeclarative;
+ }
+ }
+
+
+ // custom module records for binding graph
+ // store linking module records in a separate table
+ function getOrCreateModuleRecord(name, loader) {
+ var moduleRecords = loader.moduleRecords;
+ return moduleRecords[name] || (moduleRecords[name] = {
+ name: name,
+ dependencies: [],
+ module: new Module(), // start from an empty module and extend
+ importers: []
+ });
+ }
+
+ // custom declarative linking function
+ function linkDeclarativeModule(load, loads, loader) {
+ if (load.module)
+ return;
+
+ var module = load.module = getOrCreateModuleRecord(load.name, loader);
+ var moduleObj = load.module.module;
+
+ var registryEntry = load.declare.call(__global, function(name, value) {
+ // NB This should be an Object.defineProperty, but that is very slow.
+ // By disaling this module write-protection we gain performance.
+ // It could be useful to allow an option to enable or disable this.
+ module.locked = true;
+ moduleObj[name] = value;
+
+ for (var i = 0, l = module.importers.length; i < l; i++) {
+ var importerModule = module.importers[i];
+ if (!importerModule.locked) {
+ var importerIndex = indexOf.call(importerModule.dependencies, module);
+ importerModule.setters[importerIndex](moduleObj);
+ }
+ }
+
+ module.locked = false;
+ return value;
+ });
+
+ // setup our setters and execution function
+ module.setters = registryEntry.setters;
+ module.execute = registryEntry.execute;
+
+ // now link all the module dependencies
+ // amending the depMap as we go
+ for (var i = 0, l = load.dependencies.length; i < l; i++) {
+ var depName = load.dependencies[i].value;
+ var depModule = loader.modules[depName];
+
+ // if dependency not already in the module registry
+ // then try and link it now
+ if (!depModule) {
+ // get the dependency load record
+ for (var j = 0; j < loads.length; j++) {
+ if (loads[j].name != depName)
+ continue;
+
+ // only link if already not already started linking (stops at circular / dynamic)
+ if (!loads[j].module) {
+ linkDeclarativeModule(loads[j], loads, loader);
+ depModule = loads[j].module;
+ }
+ // if circular, create the module record
+ else {
+ depModule = getOrCreateModuleRecord(depName, loader);
+ }
+ }
+ }
+
+ // only declarative modules have dynamic bindings
+ if (depModule.importers) {
+ module.dependencies.push(depModule);
+ depModule.importers.push(module);
+ }
+ else {
+ // track dynamic records as null module records as already linked
+ module.dependencies.push(null);
+ }
+
+ // run the setter for this dependency
+ if (module.setters[i])
+ module.setters[i](depModule.module);
+ }
+
+ load.status = 'linked';
+ }
+
+
+
+ // 15.2.5.5.1 LinkImports not implemented
+ // 15.2.5.7 ResolveExportEntries not implemented
+ // 15.2.5.8 ResolveExports not implemented
+ // 15.2.5.9 ResolveExport not implemented
+ // 15.2.5.10 ResolveImportEntries not implemented
+
+ // 15.2.6.1
+ function evaluateLoadedModule(loader, load) {
+ console.assert(load.status == 'linked', 'is linked ' + load.name);
+
+ doEnsureEvaluated(load.module, [], loader);
+ return load.module.module;
+ }
+
+ /*
+ * Module Object non-exotic for ES5:
+ *
+ * module.module bound module object
+ * module.execute execution function for module
+ * module.dependencies list of module objects for dependencies
+ * See getOrCreateModuleRecord for all properties
+ *
+ */
+ function doExecute(module) {
+ try {
+ module.execute.call(__global);
+ }
+ catch(e) {
+ return e;
+ }
+ }
+
+ // propogate execution errors
+ // see https://bugs.ecmascript.org/show_bug.cgi?id=2993
+ function doEnsureEvaluated(module, seen, loader) {
+ var err = ensureEvaluated(module, seen, loader);
+ if (err)
+ throw err;
+ }
+ // 15.2.6.2 EnsureEvaluated adjusted
+ function ensureEvaluated(module, seen, loader) {
+ if (module.evaluated || !module.dependencies)
+ return;
+
+ seen.push(module);
+
+ var deps = module.dependencies;
+ var err;
+
+ for (var i = 0, l = deps.length; i < l; i++) {
+ var dep = deps[i];
+ // dynamic dependencies are empty in module.dependencies
+ // as they are already linked
+ if (!dep)
+ continue;
+ if (indexOf.call(seen, dep) == -1) {
+ err = ensureEvaluated(dep, seen, loader);
+ // stop on error, see https://bugs.ecmascript.org/show_bug.cgi?id=2996
+ if (err) {
+ err = addToError(err, 'Error evaluating ' + dep.name + '\n');
+ return err;
+ }
+ }
+ }
+
+ if (module.failed)
+ return new Error('Module failed execution.');
+
+ if (module.evaluated)
+ return;
+
+ module.evaluated = true;
+ err = doExecute(module);
+ if (err) {
+ module.failed = true;
+ }
+ else if (Object.preventExtensions) {
+ // spec variation
+ // we don't create a new module here because it was created and ammended
+ // we just disable further extensions instead
+ Object.preventExtensions(module.module);
+ }
+
+ module.execute = undefined;
+ return err;
+ }
+
+ function addToError(err, msg) {
+ if (err instanceof Error)
+ err.message = msg + err.message;
+ else
+ err = msg + err;
+ return err;
+ }
+
+ // 26.3 Loader
+
+ // 26.3.1.1
+ function Loader(options) {
+ if (typeof options != 'object')
+ throw new TypeError('Options must be an object');
+
+ if (options.normalize)
+ this.normalize = options.normalize;
+ if (options.locate)
+ this.locate = options.locate;
+ if (options.fetch)
+ this.fetch = options.fetch;
+ if (options.translate)
+ this.translate = options.translate;
+ if (options.instantiate)
+ this.instantiate = options.instantiate;
+
+ this._loader = {
+ loaderObj: this,
+ loads: [],
+ modules: {},
+ importPromises: {},
+ moduleRecords: {}
+ };
+
+ // 26.3.3.6
+ defineProperty(this, 'global', {
+ get: function() {
+ return __global;
+ }
+ });
+
+ // 26.3.3.13 realm not implemented
+ this.traceurOptions = {};
+ }
+
+ function Module() {}
+
+ // importPromises adds ability to import a module twice without error - https://bugs.ecmascript.org/show_bug.cgi?id=2601
+ function createImportPromise(loader, name, promise) {
+ var importPromises = loader._loader.importPromises;
+ return importPromises[name] = promise.then(function(m) {
+ importPromises[name] = undefined;
+ return m;
+ }, function(e) {
+ importPromises[name] = undefined;
+ throw e;
+ });
+ }
+
+ Loader.prototype = {
+ // 26.3.3.1
+ constructor: Loader,
+ // 26.3.3.2
+ define: function(name, source, options) {
+ // check if already defined
+ if (this._loader.importPromises[name])
+ throw new TypeError('Module is already loading.');
+ return createImportPromise(this, name, new Promise(asyncStartLoadPartwayThrough({
+ step: 'translate',
+ loader: this._loader,
+ moduleName: name,
+ moduleMetadata: options && options.metadata || {},
+ moduleSource: source,
+ moduleAddress: options && options.address
+ })));
+ },
+ // 26.3.3.3
+ 'delete': function(name) {
+ return this._loader.modules[name] ? delete this._loader.modules[name] : false;
+ },
+ // 26.3.3.4 entries not implemented
+ // 26.3.3.5
+ get: function(key) {
+ if (!this._loader.modules[key])
+ return;
+ doEnsureEvaluated(this._loader.modules[key], [], this);
+ return this._loader.modules[key].module;
+ },
+ // 26.3.3.7
+ has: function(name) {
+ return !!this._loader.modules[name];
+ },
+ // 26.3.3.8
+ 'import': function(name, options) {
+ // run normalize first
+ var loaderObj = this;
+
+ // added, see https://bugs.ecmascript.org/show_bug.cgi?id=2659
+ return Promise.resolve(loaderObj.normalize(name, options && options.name, options && options.address))
+ .then(function(name) {
+ var loader = loaderObj._loader;
+
+ if (loader.modules[name]) {
+ doEnsureEvaluated(loader.modules[name], [], loader._loader);
+ return loader.modules[name].module;
+ }
+
+ return loader.importPromises[name] || createImportPromise(loaderObj, name,
+ loadModule(loader, name, options || {})
+ .then(function(load) {
+ delete loader.importPromises[name];
+ return evaluateLoadedModule(loader, load);
+ }));
+ });
+ },
+ // 26.3.3.9 keys not implemented
+ // 26.3.3.10
+ load: function(name, options) {
+ if (this._loader.modules[name]) {
+ doEnsureEvaluated(this._loader.modules[name], [], this._loader);
+ return Promise.resolve(this._loader.modules[name].module);
+ }
+ return this._loader.importPromises[name] || createImportPromise(this, name, loadModule(this._loader, name, {}));
+ },
+ // 26.3.3.11
+ module: function(source, options) {
+ var load = createLoad();
+ load.address = options && options.address;
+ var linkSet = createLinkSet(this._loader, load);
+ var sourcePromise = Promise.resolve(source);
+ var loader = this._loader;
+ var p = linkSet.done.then(function() {
+ return evaluateLoadedModule(loader, load);
+ });
+ proceedToTranslate(loader, load, sourcePromise);
+ return p;
+ },
+ // 26.3.3.12
+ newModule: function (obj) {
+ if (typeof obj != 'object')
+ throw new TypeError('Expected object');
+
+ // we do this to be able to tell if a module is a module privately in ES5
+ // by doing m instanceof Module
+ var m = new Module();
+
+ for (var key in obj) {
+ (function (key) {
+ defineProperty(m, key, {
+ configurable: false,
+ enumerable: true,
+ get: function () {
+ return obj[key];
+ }
+ });
+ })(key);
+ }
+
+ if (Object.preventExtensions)
+ Object.preventExtensions(m);
+
+ return m;
+ },
+ // 26.3.3.14
+ set: function(name, module) {
+ if (!(module instanceof Module))
+ throw new TypeError('Loader.set(' + name + ', module) must be a module');
+ this._loader.modules[name] = {
+ module: module
+ };
+ },
+ // 26.3.3.15 values not implemented
+ // 26.3.3.16 @@iterator not implemented
+ // 26.3.3.17 @@toStringTag not implemented
+
+ // 26.3.3.18.1
+ normalize: function(name, referrerName, referrerAddress) {
+ return name;
+ },
+ // 26.3.3.18.2
+ locate: function(load) {
+ return load.name;
+ },
+ // 26.3.3.18.3
+ fetch: function(load) {
+ throw new TypeError('Fetch not implemented');
+ },
+ // 26.3.3.18.4
+ translate: function(load) {
+ return load.source;
+ },
+ parse: function(load) {
+ throw new TypeError('Loader.parse is not implemented');
+ },
+ // 26.3.3.18.5
+ instantiate: function(load) {
+ }
+ };
+
+ var _newModule = Loader.prototype.newModule;
+
+
+ /*
+ * Traceur-specific Parsing Code for Loader
+ */
+ (function() {
+ // parse function is used to parse a load record
+ // Returns an array of ModuleSpecifiers
+ var traceur;
+
+ function doCompile(source, compiler, filename) {
+ try {
+ return compiler.compile(source, filename);
+ }
+ catch(e) {
+ // traceur throws an error array
+ throw e[0];
+ }
+ }
+ Loader.prototype.parse = function(load) {
+ if (!traceur) {
+ if (typeof window == 'undefined' &&
+ typeof WorkerGlobalScope == 'undefined')
+ traceur = require('traceur');
+ else if (__global.traceur)
+ traceur = __global.traceur;
+ else
+ throw new TypeError('Include Traceur for module syntax support');
+ }
+
+ console.assert(load.source, 'Non-empty source');
+
+ load.isDeclarative = true;
+
+ var options = this.traceurOptions || {};
+ options.modules = 'instantiate';
+ options.script = false;
+ options.sourceMaps = 'inline';
+ options.filename = load.address;
+
+ var compiler = new traceur.Compiler(options);
+
+ var source = doCompile(load.source, compiler, options.filename);
+
+ if (!source)
+ throw new Error('Error evaluating module ' + load.address);
+
+ var sourceMap = compiler.getSourceMap();
+
+ if (__global.btoa && sourceMap) {
+ // add "!eval" to end of Traceur sourceURL
+ // I believe this does something?
+ source += '!eval';
+ }
+
+ source = 'var __moduleAddress = "' + load.address + '";' + source;
+
+ __eval(source, __global, load);
+ }
+ })();
+
+ if (typeof exports === 'object')
+ module.exports = Loader;
+
+ __global.Reflect = __global.Reflect || {};
+ __global.Reflect.Loader = __global.Reflect.Loader || Loader;
+ __global.Reflect.global = __global.Reflect.global || __global;
+ __global.LoaderPolyfill = Loader;
+
+})();
+
+/*
+*********************************************************************************************
+
+ System Loader Implementation
+
+ - Implemented to https://github.com/jorendorff/js-loaders/blob/master/browser-loader.js
+
+ -
+
+```
+
+## Documentation
+
+### Collections
+
+* [`each`](#each)
+* [`eachSeries`](#eachSeries)
+* [`eachLimit`](#eachLimit)
+* [`map`](#map)
+* [`mapSeries`](#mapSeries)
+* [`mapLimit`](#mapLimit)
+* [`filter`](#filter)
+* [`filterSeries`](#filterSeries)
+* [`reject`](#reject)
+* [`rejectSeries`](#rejectSeries)
+* [`reduce`](#reduce)
+* [`reduceRight`](#reduceRight)
+* [`detect`](#detect)
+* [`detectSeries`](#detectSeries)
+* [`sortBy`](#sortBy)
+* [`some`](#some)
+* [`every`](#every)
+* [`concat`](#concat)
+* [`concatSeries`](#concatSeries)
+
+### Control Flow
+
+* [`series`](#seriestasks-callback)
+* [`parallel`](#parallel)
+* [`parallelLimit`](#parallellimittasks-limit-callback)
+* [`whilst`](#whilst)
+* [`doWhilst`](#doWhilst)
+* [`until`](#until)
+* [`doUntil`](#doUntil)
+* [`forever`](#forever)
+* [`waterfall`](#waterfall)
+* [`compose`](#compose)
+* [`seq`](#seq)
+* [`applyEach`](#applyEach)
+* [`applyEachSeries`](#applyEachSeries)
+* [`queue`](#queue)
+* [`priorityQueue`](#priorityQueue)
+* [`cargo`](#cargo)
+* [`auto`](#auto)
+* [`retry`](#retry)
+* [`iterator`](#iterator)
+* [`apply`](#apply)
+* [`nextTick`](#nextTick)
+* [`times`](#times)
+* [`timesSeries`](#timesSeries)
+
+### Utils
+
+* [`memoize`](#memoize)
+* [`unmemoize`](#unmemoize)
+* [`log`](#log)
+* [`dir`](#dir)
+* [`noConflict`](#noConflict)
+
+
+## Collections
+
+
+
+### each(arr, iterator, callback)
+
+Applies the function `iterator` to each item in `arr`, in parallel.
+The `iterator` is called with an item from the list, and a callback for when it
+has finished. If the `iterator` passes an error to its `callback`, the main
+`callback` (for the `each` function) is immediately called with the error.
+
+Note, that since this function applies `iterator` to each item in parallel,
+there is no guarantee that the iterator functions will complete in order.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err)` which must be called once it has
+ completed. If no error has occured, the `callback` should be run without
+ arguments or with an explicit `null` argument.
+* `callback(err)` - A callback which is called when all `iterator` functions
+ have finished, or an error occurs.
+
+__Examples__
+
+
+```js
+// assuming openFiles is an array of file names and saveFile is a function
+// to save the modified contents of that file:
+
+async.each(openFiles, saveFile, function(err){
+ // if any of the saves produced an error, err would equal that error
+});
+```
+
+```js
+// assuming openFiles is an array of file names
+
+async.each(openFiles, function( file, callback) {
+
+ // Perform operation on file here.
+ console.log('Processing file ' + file);
+
+ if( file.length > 32 ) {
+ console.log('This file name is too long');
+ callback('File name too long');
+ } else {
+ // Do work to process file here
+ console.log('File processed');
+ callback();
+ }
+}, function(err){
+ // if any of the file processing produced an error, err would equal that error
+ if( err ) {
+ // One of the iterations produced an error.
+ // All processing will now stop.
+ console.log('A file failed to process');
+ } else {
+ console.log('All files have been processed successfully');
+ }
+});
+```
+
+---------------------------------------
+
+
+
+### eachSeries(arr, iterator, callback)
+
+The same as [`each`](#each), only `iterator` is applied to each item in `arr` in
+series. The next `iterator` is only called once the current one has completed.
+This means the `iterator` functions will complete in order.
+
+
+---------------------------------------
+
+
+
+### eachLimit(arr, limit, iterator, callback)
+
+The same as [`each`](#each), only no more than `limit` `iterator`s will be simultaneously
+running at any time.
+
+Note that the items in `arr` are not processed in batches, so there is no guarantee that
+the first `limit` `iterator` functions will complete before any others are started.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `limit` - The maximum number of `iterator`s to run at any time.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err)` which must be called once it has
+ completed. If no error has occured, the callback should be run without
+ arguments or with an explicit `null` argument.
+* `callback(err)` - A callback which is called when all `iterator` functions
+ have finished, or an error occurs.
+
+__Example__
+
+```js
+// Assume documents is an array of JSON objects and requestApi is a
+// function that interacts with a rate-limited REST api.
+
+async.eachLimit(documents, 20, requestApi, function(err){
+ // if any of the saves produced an error, err would equal that error
+});
+```
+
+---------------------------------------
+
+
+### map(arr, iterator, callback)
+
+Produces a new array of values by mapping each value in `arr` through
+the `iterator` function. The `iterator` is called with an item from `arr` and a
+callback for when it has finished processing. Each of these callback takes 2 arguments:
+an `error`, and the transformed item from `arr`. If `iterator` passes an error to this
+callback, the main `callback` (for the `map` function) is immediately called with the error.
+
+Note, that since this function applies the `iterator` to each item in parallel,
+there is no guarantee that the `iterator` functions will complete in order.
+However, the results array will be in the same order as the original `arr`.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err, transformed)` which must be called once
+ it has completed with an error (which can be `null`) and a transformed item.
+* `callback(err, results)` - A callback which is called when all `iterator`
+ functions have finished, or an error occurs. Results is an array of the
+ transformed items from the `arr`.
+
+__Example__
+
+```js
+async.map(['file1','file2','file3'], fs.stat, function(err, results){
+ // results is now an array of stats for each file
+});
+```
+
+---------------------------------------
+
+
+### mapSeries(arr, iterator, callback)
+
+The same as [`map`](#map), only the `iterator` is applied to each item in `arr` in
+series. The next `iterator` is only called once the current one has completed.
+The results array will be in the same order as the original.
+
+
+---------------------------------------
+
+
+### mapLimit(arr, limit, iterator, callback)
+
+The same as [`map`](#map), only no more than `limit` `iterator`s will be simultaneously
+running at any time.
+
+Note that the items are not processed in batches, so there is no guarantee that
+the first `limit` `iterator` functions will complete before any others are started.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `limit` - The maximum number of `iterator`s to run at any time.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err, transformed)` which must be called once
+ it has completed with an error (which can be `null`) and a transformed item.
+* `callback(err, results)` - A callback which is called when all `iterator`
+ calls have finished, or an error occurs. The result is an array of the
+ transformed items from the original `arr`.
+
+__Example__
+
+```js
+async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){
+ // results is now an array of stats for each file
+});
+```
+
+---------------------------------------
+
+
+
+### filter(arr, iterator, callback)
+
+__Alias:__ `select`
+
+Returns a new array of all the values in `arr` which pass an async truth test.
+_The callback for each `iterator` call only accepts a single argument of `true` or
+`false`; it does not accept an error argument first!_ This is in-line with the
+way node libraries work with truth tests like `fs.exists`. This operation is
+performed in parallel, but the results array will be in the same order as the
+original.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in `arr`.
+ The `iterator` is passed a `callback(truthValue)`, which must be called with a
+ boolean argument once it has completed.
+* `callback(results)` - A callback which is called after all the `iterator`
+ functions have finished.
+
+__Example__
+
+```js
+async.filter(['file1','file2','file3'], fs.exists, function(results){
+ // results now equals an array of the existing files
+});
+```
+
+---------------------------------------
+
+
+
+### filterSeries(arr, iterator, callback)
+
+__Alias:__ `selectSeries`
+
+The same as [`filter`](#filter) only the `iterator` is applied to each item in `arr` in
+series. The next `iterator` is only called once the current one has completed.
+The results array will be in the same order as the original.
+
+---------------------------------------
+
+
+### reject(arr, iterator, callback)
+
+The opposite of [`filter`](#filter). Removes values that pass an `async` truth test.
+
+---------------------------------------
+
+
+### rejectSeries(arr, iterator, callback)
+
+The same as [`reject`](#reject), only the `iterator` is applied to each item in `arr`
+in series.
+
+
+---------------------------------------
+
+
+### reduce(arr, memo, iterator, callback)
+
+__Aliases:__ `inject`, `foldl`
+
+Reduces `arr` into a single value using an async `iterator` to return
+each successive step. `memo` is the initial state of the reduction.
+This function only operates in series.
+
+For performance reasons, it may make sense to split a call to this function into
+a parallel map, and then use the normal `Array.prototype.reduce` on the results.
+This function is for situations where each step in the reduction needs to be async;
+if you can get the data before reducing it, then it's probably a good idea to do so.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `memo` - The initial state of the reduction.
+* `iterator(memo, item, callback)` - A function applied to each item in the
+ array to produce the next step in the reduction. The `iterator` is passed a
+ `callback(err, reduction)` which accepts an optional error as its first
+ argument, and the state of the reduction as the second. If an error is
+ passed to the callback, the reduction is stopped and the main `callback` is
+ immediately called with the error.
+* `callback(err, result)` - A callback which is called after all the `iterator`
+ functions have finished. Result is the reduced value.
+
+__Example__
+
+```js
+async.reduce([1,2,3], 0, function(memo, item, callback){
+ // pointless async:
+ process.nextTick(function(){
+ callback(null, memo + item)
+ });
+}, function(err, result){
+ // result is now equal to the last value of memo, which is 6
+});
+```
+
+---------------------------------------
+
+
+### reduceRight(arr, memo, iterator, callback)
+
+__Alias:__ `foldr`
+
+Same as [`reduce`](#reduce), only operates on `arr` in reverse order.
+
+
+---------------------------------------
+
+
+### detect(arr, iterator, callback)
+
+Returns the first value in `arr` that passes an async truth test. The
+`iterator` is applied in parallel, meaning the first iterator to return `true` will
+fire the detect `callback` with that result. That means the result might not be
+the first item in the original `arr` (in terms of order) that passes the test.
+
+If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries).
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in `arr`.
+ The iterator is passed a `callback(truthValue)` which must be called with a
+ boolean argument once it has completed.
+* `callback(result)` - A callback which is called as soon as any iterator returns
+ `true`, or after all the `iterator` functions have finished. Result will be
+ the first item in the array that passes the truth test (iterator) or the
+ value `undefined` if none passed.
+
+__Example__
+
+```js
+async.detect(['file1','file2','file3'], fs.exists, function(result){
+ // result now equals the first file in the list that exists
+});
+```
+
+---------------------------------------
+
+
+### detectSeries(arr, iterator, callback)
+
+The same as [`detect`](#detect), only the `iterator` is applied to each item in `arr`
+in series. This means the result is always the first in the original `arr` (in
+terms of array order) that passes the truth test.
+
+
+---------------------------------------
+
+
+### sortBy(arr, iterator, callback)
+
+Sorts a list by the results of running each `arr` value through an async `iterator`.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err, sortValue)` which must be called once it
+ has completed with an error (which can be `null`) and a value to use as the sort
+ criteria.
+* `callback(err, results)` - A callback which is called after all the `iterator`
+ functions have finished, or an error occurs. Results is the items from
+ the original `arr` sorted by the values returned by the `iterator` calls.
+
+__Example__
+
+```js
+async.sortBy(['file1','file2','file3'], function(file, callback){
+ fs.stat(file, function(err, stats){
+ callback(err, stats.mtime);
+ });
+}, function(err, results){
+ // results is now the original array of files sorted by
+ // modified date
+});
+```
+
+__Sort Order__
+
+By modifying the callback parameter the sorting order can be influenced:
+
+```js
+//ascending order
+async.sortBy([1,9,3,5], function(x, callback){
+ callback(err, x);
+}, function(err,result){
+ //result callback
+} );
+
+//descending order
+async.sortBy([1,9,3,5], function(x, callback){
+ callback(err, x*-1); //<- x*-1 instead of x, turns the order around
+}, function(err,result){
+ //result callback
+} );
+```
+
+---------------------------------------
+
+
+### some(arr, iterator, callback)
+
+__Alias:__ `any`
+
+Returns `true` if at least one element in the `arr` satisfies an async test.
+_The callback for each iterator call only accepts a single argument of `true` or
+`false`; it does not accept an error argument first!_ This is in-line with the
+way node libraries work with truth tests like `fs.exists`. Once any iterator
+call returns `true`, the main `callback` is immediately called.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in the array
+ in parallel. The iterator is passed a callback(truthValue) which must be
+ called with a boolean argument once it has completed.
+* `callback(result)` - A callback which is called as soon as any iterator returns
+ `true`, or after all the iterator functions have finished. Result will be
+ either `true` or `false` depending on the values of the async tests.
+
+__Example__
+
+```js
+async.some(['file1','file2','file3'], fs.exists, function(result){
+ // if result is true then at least one of the files exists
+});
+```
+
+---------------------------------------
+
+
+### every(arr, iterator, callback)
+
+__Alias:__ `all`
+
+Returns `true` if every element in `arr` satisfies an async test.
+_The callback for each `iterator` call only accepts a single argument of `true` or
+`false`; it does not accept an error argument first!_ This is in-line with the
+way node libraries work with truth tests like `fs.exists`.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in the array
+ in parallel. The iterator is passed a callback(truthValue) which must be
+ called with a boolean argument once it has completed.
+* `callback(result)` - A callback which is called after all the `iterator`
+ functions have finished. Result will be either `true` or `false` depending on
+ the values of the async tests.
+
+__Example__
+
+```js
+async.every(['file1','file2','file3'], fs.exists, function(result){
+ // if result is true then every file exists
+});
+```
+
+---------------------------------------
+
+
+### concat(arr, iterator, callback)
+
+Applies `iterator` to each item in `arr`, concatenating the results. Returns the
+concatenated list. The `iterator`s are called in parallel, and the results are
+concatenated as they return. There is no guarantee that the results array will
+be returned in the original order of `arr` passed to the `iterator` function.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err, results)` which must be called once it
+ has completed with an error (which can be `null`) and an array of results.
+* `callback(err, results)` - A callback which is called after all the `iterator`
+ functions have finished, or an error occurs. Results is an array containing
+ the concatenated results of the `iterator` function.
+
+__Example__
+
+```js
+async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
+ // files is now a list of filenames that exist in the 3 directories
+});
+```
+
+---------------------------------------
+
+
+### concatSeries(arr, iterator, callback)
+
+Same as [`concat`](#concat), but executes in series instead of parallel.
+
+
+## Control Flow
+
+
+### series(tasks, [callback])
+
+Run the functions in the `tasks` array in series, each one running once the previous
+function has completed. If any functions in the series pass an error to its
+callback, no more functions are run, and `callback` is immediately called with the value of the error.
+Otherwise, `callback` receives an array of results when `tasks` have completed.
+
+It is also possible to use an object instead of an array. Each property will be
+run as a function, and the results will be passed to the final `callback` as an object
+instead of an array. This can be a more readable way of handling results from
+[`series`](#series).
+
+**Note** that while many implementations preserve the order of object properties, the
+[ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
+explicitly states that
+
+> The mechanics and order of enumerating the properties is not specified.
+
+So if you rely on the order in which your series of functions are executed, and want
+this to work on all platforms, consider using an array.
+
+__Arguments__
+
+* `tasks` - An array or object containing functions to run, each function is passed
+ a `callback(err, result)` it must call on completion with an error `err` (which can
+ be `null`) and an optional `result` value.
+* `callback(err, results)` - An optional callback to run once all the functions
+ have completed. This function gets a results array (or object) containing all
+ the result arguments passed to the `task` callbacks.
+
+__Example__
+
+```js
+async.series([
+ function(callback){
+ // do some stuff ...
+ callback(null, 'one');
+ },
+ function(callback){
+ // do some more stuff ...
+ callback(null, 'two');
+ }
+],
+// optional callback
+function(err, results){
+ // results is now equal to ['one', 'two']
+});
+
+
+// an example using an object instead of an array
+async.series({
+ one: function(callback){
+ setTimeout(function(){
+ callback(null, 1);
+ }, 200);
+ },
+ two: function(callback){
+ setTimeout(function(){
+ callback(null, 2);
+ }, 100);
+ }
+},
+function(err, results) {
+ // results is now equal to: {one: 1, two: 2}
+});
+```
+
+---------------------------------------
+
+
+### parallel(tasks, [callback])
+
+Run the `tasks` array of functions in parallel, without waiting until the previous
+function has completed. If any of the functions pass an error to its
+callback, the main `callback` is immediately called with the value of the error.
+Once the `tasks` have completed, the results are passed to the final `callback` as an
+array.
+
+It is also possible to use an object instead of an array. Each property will be
+run as a function and the results will be passed to the final `callback` as an object
+instead of an array. This can be a more readable way of handling results from
+[`parallel`](#parallel).
+
+
+__Arguments__
+
+* `tasks` - An array or object containing functions to run. Each function is passed
+ a `callback(err, result)` which it must call on completion with an error `err`
+ (which can be `null`) and an optional `result` value.
+* `callback(err, results)` - An optional callback to run once all the functions
+ have completed. This function gets a results array (or object) containing all
+ the result arguments passed to the task callbacks.
+
+__Example__
+
+```js
+async.parallel([
+ function(callback){
+ setTimeout(function(){
+ callback(null, 'one');
+ }, 200);
+ },
+ function(callback){
+ setTimeout(function(){
+ callback(null, 'two');
+ }, 100);
+ }
+],
+// optional callback
+function(err, results){
+ // the results array will equal ['one','two'] even though
+ // the second function had a shorter timeout.
+});
+
+
+// an example using an object instead of an array
+async.parallel({
+ one: function(callback){
+ setTimeout(function(){
+ callback(null, 1);
+ }, 200);
+ },
+ two: function(callback){
+ setTimeout(function(){
+ callback(null, 2);
+ }, 100);
+ }
+},
+function(err, results) {
+ // results is now equals to: {one: 1, two: 2}
+});
+```
+
+---------------------------------------
+
+
+### parallelLimit(tasks, limit, [callback])
+
+The same as [`parallel`](#parallel), only `tasks` are executed in parallel
+with a maximum of `limit` tasks executing at any time.
+
+Note that the `tasks` are not executed in batches, so there is no guarantee that
+the first `limit` tasks will complete before any others are started.
+
+__Arguments__
+
+* `tasks` - An array or object containing functions to run, each function is passed
+ a `callback(err, result)` it must call on completion with an error `err` (which can
+ be `null`) and an optional `result` value.
+* `limit` - The maximum number of `tasks` to run at any time.
+* `callback(err, results)` - An optional callback to run once all the functions
+ have completed. This function gets a results array (or object) containing all
+ the result arguments passed to the `task` callbacks.
+
+---------------------------------------
+
+
+### whilst(test, fn, callback)
+
+Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped,
+or an error occurs.
+
+__Arguments__
+
+* `test()` - synchronous truth test to perform before each execution of `fn`.
+* `fn(callback)` - A function which is called each time `test` passes. The function is
+ passed a `callback(err)`, which must be called once it has completed with an
+ optional `err` argument.
+* `callback(err)` - A callback which is called after the test fails and repeated
+ execution of `fn` has stopped.
+
+__Example__
+
+```js
+var count = 0;
+
+async.whilst(
+ function () { return count < 5; },
+ function (callback) {
+ count++;
+ setTimeout(callback, 1000);
+ },
+ function (err) {
+ // 5 seconds have passed
+ }
+);
+```
+
+---------------------------------------
+
+
+### doWhilst(fn, test, callback)
+
+The post-check version of [`whilst`](#whilst). To reflect the difference in
+the order of operations, the arguments `test` and `fn` are switched.
+
+`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
+
+---------------------------------------
+
+
+### until(test, fn, callback)
+
+Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped,
+or an error occurs.
+
+The inverse of [`whilst`](#whilst).
+
+---------------------------------------
+
+
+### doUntil(fn, test, callback)
+
+Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`.
+
+---------------------------------------
+
+
+### forever(fn, errback)
+
+Calls the asynchronous function `fn` with a callback parameter that allows it to
+call itself again, in series, indefinitely.
+
+If an error is passed to the callback then `errback` is called with the
+error, and execution stops, otherwise it will never be called.
+
+```js
+async.forever(
+ function(next) {
+ // next is suitable for passing to things that need a callback(err [, whatever]);
+ // it will result in this function being called again.
+ },
+ function(err) {
+ // if next is called with a value in its first parameter, it will appear
+ // in here as 'err', and execution will stop.
+ }
+);
+```
+
+---------------------------------------
+
+
+### waterfall(tasks, [callback])
+
+Runs the `tasks` array of functions in series, each passing their results to the next in
+the array. However, if any of the `tasks` pass an error to their own callback, the
+next function is not executed, and the main `callback` is immediately called with
+the error.
+
+__Arguments__
+
+* `tasks` - An array of functions to run, each function is passed a
+ `callback(err, result1, result2, ...)` it must call on completion. The first
+ argument is an error (which can be `null`) and any further arguments will be
+ passed as arguments in order to the next task.
+* `callback(err, [results])` - An optional callback to run once all the functions
+ have completed. This will be passed the results of the last task's callback.
+
+
+
+__Example__
+
+```js
+async.waterfall([
+ function(callback){
+ callback(null, 'one', 'two');
+ },
+ function(arg1, arg2, callback){
+ // arg1 now equals 'one' and arg2 now equals 'two'
+ callback(null, 'three');
+ },
+ function(arg1, callback){
+ // arg1 now equals 'three'
+ callback(null, 'done');
+ }
+], function (err, result) {
+ // result now equals 'done'
+});
+```
+
+---------------------------------------
+
+### compose(fn1, fn2...)
+
+Creates a function which is a composition of the passed asynchronous
+functions. Each function consumes the return value of the function that
+follows. Composing functions `f()`, `g()`, and `h()` would produce the result of
+`f(g(h()))`, only this version uses callbacks to obtain the return values.
+
+Each function is executed with the `this` binding of the composed function.
+
+__Arguments__
+
+* `functions...` - the asynchronous functions to compose
+
+
+__Example__
+
+```js
+function add1(n, callback) {
+ setTimeout(function () {
+ callback(null, n + 1);
+ }, 10);
+}
+
+function mul3(n, callback) {
+ setTimeout(function () {
+ callback(null, n * 3);
+ }, 10);
+}
+
+var add1mul3 = async.compose(mul3, add1);
+
+add1mul3(4, function (err, result) {
+ // result now equals 15
+});
+```
+
+---------------------------------------
+
+### seq(fn1, fn2...)
+
+Version of the compose function that is more natural to read.
+Each following function consumes the return value of the latter function.
+
+Each function is executed with the `this` binding of the composed function.
+
+__Arguments__
+
+* functions... - the asynchronous functions to compose
+
+
+__Example__
+
+```js
+// Requires lodash (or underscore), express3 and dresende's orm2.
+// Part of an app, that fetches cats of the logged user.
+// This example uses `seq` function to avoid overnesting and error
+// handling clutter.
+app.get('/cats', function(request, response) {
+ function handleError(err, data, callback) {
+ if (err) {
+ console.error(err);
+ response.json({ status: 'error', message: err.message });
+ }
+ else {
+ callback(data);
+ }
+ }
+ var User = request.models.User;
+ async.seq(
+ _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
+ handleError,
+ function(user, fn) {
+ user.getCats(fn); // 'getCats' has signature (callback(err, data))
+ },
+ handleError,
+ function(cats) {
+ response.json({ status: 'ok', message: 'Cats found', data: cats });
+ }
+ )(req.session.user_id);
+ }
+});
+```
+
+---------------------------------------
+
+### applyEach(fns, args..., callback)
+
+Applies the provided arguments to each function in the array, calling
+`callback` after all functions have completed. If you only provide the first
+argument, then it will return a function which lets you pass in the
+arguments as if it were a single function call.
+
+__Arguments__
+
+* `fns` - the asynchronous functions to all call with the same arguments
+* `args...` - any number of separate arguments to pass to the function
+* `callback` - the final argument should be the callback, called when all
+ functions have completed processing
+
+
+__Example__
+
+```js
+async.applyEach([enableSearch, updateSchema], 'bucket', callback);
+
+// partial application example:
+async.each(
+ buckets,
+ async.applyEach([enableSearch, updateSchema]),
+ callback
+);
+```
+
+---------------------------------------
+
+
+### applyEachSeries(arr, iterator, callback)
+
+The same as [`applyEach`](#applyEach) only the functions are applied in series.
+
+---------------------------------------
+
+
+### queue(worker, concurrency)
+
+Creates a `queue` object with the specified `concurrency`. Tasks added to the
+`queue` are processed in parallel (up to the `concurrency` limit). If all
+`worker`s are in progress, the task is queued until one becomes available.
+Once a `worker` completes a `task`, that `task`'s callback is called.
+
+__Arguments__
+
+* `worker(task, callback)` - An asynchronous function for processing a queued
+ task, which must call its `callback(err)` argument when finished, with an
+ optional `error` as an argument.
+* `concurrency` - An `integer` for determining how many `worker` functions should be
+ run in parallel.
+
+__Queue objects__
+
+The `queue` object returned by this function has the following properties and
+methods:
+
+* `length()` - a function returning the number of items waiting to be processed.
+* `started` - a function returning whether or not any items have been pushed and processed by the queue
+* `running()` - a function returning the number of items currently being processed.
+* `idle()` - a function returning false if there are items waiting or being processed, or true if not.
+* `concurrency` - an integer for determining how many `worker` functions should be
+ run in parallel. This property can be changed after a `queue` is created to
+ alter the concurrency on-the-fly.
+* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once
+ the `worker` has finished processing the task. Instead of a single task, a `tasks` array
+ can be submitted. The respective callback is used for every task in the list.
+* `unshift(task, [callback])` - add a new task to the front of the `queue`.
+* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit,
+ and further tasks will be queued.
+* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`.
+* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`.
+* `paused` - a boolean for determining whether the queue is in a paused state
+* `pause()` - a function that pauses the processing of tasks until `resume()` is called.
+* `resume()` - a function that resumes the processing of queued tasks when the queue is paused.
+* `kill()` - a function that empties remaining tasks from the queue forcing it to go idle.
+
+__Example__
+
+```js
+// create a queue object with concurrency 2
+
+var q = async.queue(function (task, callback) {
+ console.log('hello ' + task.name);
+ callback();
+}, 2);
+
+
+// assign a callback
+q.drain = function() {
+ console.log('all items have been processed');
+}
+
+// add some items to the queue
+
+q.push({name: 'foo'}, function (err) {
+ console.log('finished processing foo');
+});
+q.push({name: 'bar'}, function (err) {
+ console.log('finished processing bar');
+});
+
+// add some items to the queue (batch-wise)
+
+q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {
+ console.log('finished processing bar');
+});
+
+// add some items to the front of the queue
+
+q.unshift({name: 'bar'}, function (err) {
+ console.log('finished processing bar');
+});
+```
+
+
+---------------------------------------
+
+
+### priorityQueue(worker, concurrency)
+
+The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects:
+
+* `push(task, priority, [callback])` - `priority` should be a number. If an array of
+ `tasks` is given, all tasks will be assigned the same priority.
+* The `unshift` method was removed.
+
+---------------------------------------
+
+
+### cargo(worker, [payload])
+
+Creates a `cargo` object with the specified payload. Tasks added to the
+cargo will be processed altogether (up to the `payload` limit). If the
+`worker` is in progress, the task is queued until it becomes available. Once
+the `worker` has completed some tasks, each callback of those tasks is called.
+Check out [this animation](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) for how `cargo` and `queue` work.
+
+While [queue](#queue) passes only one task to one of a group of workers
+at a time, cargo passes an array of tasks to a single worker, repeating
+when the worker is finished.
+
+__Arguments__
+
+* `worker(tasks, callback)` - An asynchronous function for processing an array of
+ queued tasks, which must call its `callback(err)` argument when finished, with
+ an optional `err` argument.
+* `payload` - An optional `integer` for determining how many tasks should be
+ processed per round; if omitted, the default is unlimited.
+
+__Cargo objects__
+
+The `cargo` object returned by this function has the following properties and
+methods:
+
+* `length()` - A function returning the number of items waiting to be processed.
+* `payload` - An `integer` for determining how many tasks should be
+ process per round. This property can be changed after a `cargo` is created to
+ alter the payload on-the-fly.
+* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called
+ once the `worker` has finished processing the task. Instead of a single task, an array of `tasks`
+ can be submitted. The respective callback is used for every task in the list.
+* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued.
+* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`.
+* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`.
+
+__Example__
+
+```js
+// create a cargo object with payload 2
+
+var cargo = async.cargo(function (tasks, callback) {
+ for(var i=0; i
+### auto(tasks, [callback])
+
+Determines the best order for running the functions in `tasks`, based on their
+requirements. Each function can optionally depend on other functions being completed
+first, and each function is run as soon as its requirements are satisfied.
+
+If any of the functions pass an error to their callback, it will not
+complete (so any other functions depending on it will not run), and the main
+`callback` is immediately called with the error. Functions also receive an
+object containing the results of functions which have completed so far.
+
+Note, all functions are called with a `results` object as a second argument,
+so it is unsafe to pass functions in the `tasks` object which cannot handle the
+extra argument.
+
+For example, this snippet of code:
+
+```js
+async.auto({
+ readData: async.apply(fs.readFile, 'data.txt', 'utf-8')
+}, callback);
+```
+
+will have the effect of calling `readFile` with the results object as the last
+argument, which will fail:
+
+```js
+fs.readFile('data.txt', 'utf-8', cb, {});
+```
+
+Instead, wrap the call to `readFile` in a function which does not forward the
+`results` object:
+
+```js
+async.auto({
+ readData: function(cb, results){
+ fs.readFile('data.txt', 'utf-8', cb);
+ }
+}, callback);
+```
+
+__Arguments__
+
+* `tasks` - An object. Each of its properties is either a function or an array of
+ requirements, with the function itself the last item in the array. The object's key
+ of a property serves as the name of the task defined by that property,
+ i.e. can be used when specifying requirements for other tasks.
+ The function receives two arguments: (1) a `callback(err, result)` which must be
+ called when finished, passing an `error` (which can be `null`) and the result of
+ the function's execution, and (2) a `results` object, containing the results of
+ the previously executed functions.
+* `callback(err, results)` - An optional callback which is called when all the
+ tasks have been completed. It receives the `err` argument if any `tasks`
+ pass an error to their callback. Results are always returned; however, if
+ an error occurs, no further `tasks` will be performed, and the results
+ object will only contain partial results.
+
+
+__Example__
+
+```js
+async.auto({
+ get_data: function(callback){
+ console.log('in get_data');
+ // async code to get some data
+ callback(null, 'data', 'converted to array');
+ },
+ make_folder: function(callback){
+ console.log('in make_folder');
+ // async code to create a directory to store a file in
+ // this is run at the same time as getting the data
+ callback(null, 'folder');
+ },
+ write_file: ['get_data', 'make_folder', function(callback, results){
+ console.log('in write_file', JSON.stringify(results));
+ // once there is some data and the directory exists,
+ // write the data to a file in the directory
+ callback(null, 'filename');
+ }],
+ email_link: ['write_file', function(callback, results){
+ console.log('in email_link', JSON.stringify(results));
+ // once the file is written let's email a link to it...
+ // results.write_file contains the filename returned by write_file.
+ callback(null, {'file':results.write_file, 'email':'user@example.com'});
+ }]
+}, function(err, results) {
+ console.log('err = ', err);
+ console.log('results = ', results);
+});
+```
+
+This is a fairly trivial example, but to do this using the basic parallel and
+series functions would look like this:
+
+```js
+async.parallel([
+ function(callback){
+ console.log('in get_data');
+ // async code to get some data
+ callback(null, 'data', 'converted to array');
+ },
+ function(callback){
+ console.log('in make_folder');
+ // async code to create a directory to store a file in
+ // this is run at the same time as getting the data
+ callback(null, 'folder');
+ }
+],
+function(err, results){
+ async.series([
+ function(callback){
+ console.log('in write_file', JSON.stringify(results));
+ // once there is some data and the directory exists,
+ // write the data to a file in the directory
+ results.push('filename');
+ callback(null);
+ },
+ function(callback){
+ console.log('in email_link', JSON.stringify(results));
+ // once the file is written let's email a link to it...
+ callback(null, {'file':results.pop(), 'email':'user@example.com'});
+ }
+ ]);
+});
+```
+
+For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding
+new tasks much easier (and the code more readable).
+
+
+---------------------------------------
+
+
+### retry([times = 5], task, [callback])
+
+Attempts to get a successful response from `task` no more than `times` times before
+returning an error. If the task is successful, the `callback` will be passed the result
+of the successfull task. If all attemps fail, the callback will be passed the error and
+result (if any) of the final attempt.
+
+__Arguments__
+
+* `times` - An integer indicating how many times to attempt the `task` before giving up. Defaults to 5.
+* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)`
+ which must be called when finished, passing `err` (which can be `null`) and the `result` of
+ the function's execution, and (2) a `results` object, containing the results of
+ the previously executed functions (if nested inside another control flow).
+* `callback(err, results)` - An optional callback which is called when the
+ task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`.
+
+The [`retry`](#retry) function can be used as a stand-alone control flow by passing a
+callback, as shown below:
+
+```js
+async.retry(3, apiMethod, function(err, result) {
+ // do something with the result
+});
+```
+
+It can also be embeded within other control flow functions to retry individual methods
+that are not as reliable, like this:
+
+```js
+async.auto({
+ users: api.getUsers.bind(api),
+ payments: async.retry(3, api.getPayments.bind(api))
+}, function(err, results) {
+ // do something with the results
+});
+```
+
+
+---------------------------------------
+
+
+### iterator(tasks)
+
+Creates an iterator function which calls the next function in the `tasks` array,
+returning a continuation to call the next one after that. It's also possible to
+“peek” at the next iterator with `iterator.next()`.
+
+This function is used internally by the `async` module, but can be useful when
+you want to manually control the flow of functions in series.
+
+__Arguments__
+
+* `tasks` - An array of functions to run.
+
+__Example__
+
+```js
+var iterator = async.iterator([
+ function(){ sys.p('one'); },
+ function(){ sys.p('two'); },
+ function(){ sys.p('three'); }
+]);
+
+node> var iterator2 = iterator();
+'one'
+node> var iterator3 = iterator2();
+'two'
+node> iterator3();
+'three'
+node> var nextfn = iterator2.next();
+node> nextfn();
+'three'
+```
+
+---------------------------------------
+
+
+### apply(function, arguments..)
+
+Creates a continuation function with some arguments already applied.
+
+Useful as a shorthand when combined with other control flow functions. Any arguments
+passed to the returned function are added to the arguments originally passed
+to apply.
+
+__Arguments__
+
+* `function` - The function you want to eventually apply all arguments to.
+* `arguments...` - Any number of arguments to automatically apply when the
+ continuation is called.
+
+__Example__
+
+```js
+// using apply
+
+async.parallel([
+ async.apply(fs.writeFile, 'testfile1', 'test1'),
+ async.apply(fs.writeFile, 'testfile2', 'test2'),
+]);
+
+
+// the same process without using apply
+
+async.parallel([
+ function(callback){
+ fs.writeFile('testfile1', 'test1', callback);
+ },
+ function(callback){
+ fs.writeFile('testfile2', 'test2', callback);
+ }
+]);
+```
+
+It's possible to pass any number of additional arguments when calling the
+continuation:
+
+```js
+node> var fn = async.apply(sys.puts, 'one');
+node> fn('two', 'three');
+one
+two
+three
+```
+
+---------------------------------------
+
+
+### nextTick(callback)
+
+Calls `callback` on a later loop around the event loop. In Node.js this just
+calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)`
+if available, otherwise `setTimeout(callback, 0)`, which means other higher priority
+events may precede the execution of `callback`.
+
+This is used internally for browser-compatibility purposes.
+
+__Arguments__
+
+* `callback` - The function to call on a later loop around the event loop.
+
+__Example__
+
+```js
+var call_order = [];
+async.nextTick(function(){
+ call_order.push('two');
+ // call_order now equals ['one','two']
+});
+call_order.push('one')
+```
+
+
+### times(n, callback)
+
+Calls the `callback` function `n` times, and accumulates results in the same manner
+you would use with [`map`](#map).
+
+__Arguments__
+
+* `n` - The number of times to run the function.
+* `callback` - The function to call `n` times.
+
+__Example__
+
+```js
+// Pretend this is some complicated async factory
+var createUser = function(id, callback) {
+ callback(null, {
+ id: 'user' + id
+ })
+}
+// generate 5 users
+async.times(5, function(n, next){
+ createUser(n, function(err, user) {
+ next(err, user)
+ })
+}, function(err, users) {
+ // we should now have 5 users
+});
+```
+
+
+### timesSeries(n, callback)
+
+The same as [`times`](#times), only the iterator is applied to each item in `arr` in
+series. The next `iterator` is only called once the current one has completed.
+The results array will be in the same order as the original.
+
+
+## Utils
+
+
+### memoize(fn, [hasher])
+
+Caches the results of an `async` function. When creating a hash to store function
+results against, the callback is omitted from the hash and an optional hash
+function can be used.
+
+The cache of results is exposed as the `memo` property of the function returned
+by `memoize`.
+
+__Arguments__
+
+* `fn` - The function to proxy and cache results from.
+* `hasher` - Tn optional function for generating a custom hash for storing
+ results. It has all the arguments applied to it apart from the callback, and
+ must be synchronous.
+
+__Example__
+
+```js
+var slow_fn = function (name, callback) {
+ // do something
+ callback(null, result);
+};
+var fn = async.memoize(slow_fn);
+
+// fn can now be used as if it were slow_fn
+fn('some name', function () {
+ // callback
+});
+```
+
+
+### unmemoize(fn)
+
+Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized
+form. Handy for testing.
+
+__Arguments__
+
+* `fn` - the memoized function
+
+
+### log(function, arguments)
+
+Logs the result of an `async` function to the `console`. Only works in Node.js or
+in browsers that support `console.log` and `console.error` (such as FF and Chrome).
+If multiple arguments are returned from the async function, `console.log` is
+called on each argument in order.
+
+__Arguments__
+
+* `function` - The function you want to eventually apply all arguments to.
+* `arguments...` - Any number of arguments to apply to the function.
+
+__Example__
+
+```js
+var hello = function(name, callback){
+ setTimeout(function(){
+ callback(null, 'hello ' + name);
+ }, 1000);
+};
+```
+```js
+node> async.log(hello, 'world');
+'hello world'
+```
+
+---------------------------------------
+
+
+### dir(function, arguments)
+
+Logs the result of an `async` function to the `console` using `console.dir` to
+display the properties of the resulting object. Only works in Node.js or
+in browsers that support `console.dir` and `console.error` (such as FF and Chrome).
+If multiple arguments are returned from the async function, `console.dir` is
+called on each argument in order.
+
+__Arguments__
+
+* `function` - The function you want to eventually apply all arguments to.
+* `arguments...` - Any number of arguments to apply to the function.
+
+__Example__
+
+```js
+var hello = function(name, callback){
+ setTimeout(function(){
+ callback(null, {hello: name});
+ }, 1000);
+};
+```
+```js
+node> async.dir(hello, 'world');
+{hello: 'world'}
+```
+
+---------------------------------------
+
+
+### noConflict()
+
+Changes the value of `async` back to its original value, returning a reference to the
+`async` object.
diff --git a/node_modules/async/component.json b/node_modules/async/component.json
new file mode 100644
index 0000000..bbb0115
--- /dev/null
+++ b/node_modules/async/component.json
@@ -0,0 +1,11 @@
+{
+ "name": "async",
+ "repo": "caolan/async",
+ "description": "Higher-order functions and common patterns for asynchronous code",
+ "version": "0.1.23",
+ "keywords": [],
+ "dependencies": {},
+ "development": {},
+ "main": "lib/async.js",
+ "scripts": [ "lib/async.js" ]
+}
diff --git a/node_modules/async/lib/async.js b/node_modules/async/lib/async.js
new file mode 100755
index 0000000..01e8afc
--- /dev/null
+++ b/node_modules/async/lib/async.js
@@ -0,0 +1,1123 @@
+/*!
+ * async
+ * https://github.com/caolan/async
+ *
+ * Copyright 2010-2014 Caolan McMahon
+ * Released under the MIT license
+ */
+/*jshint onevar: false, indent:4 */
+/*global setImmediate: false, setTimeout: false, console: false */
+(function () {
+
+ var async = {};
+
+ // global on the server, window in the browser
+ var root, previous_async;
+
+ root = this;
+ if (root != null) {
+ previous_async = root.async;
+ }
+
+ async.noConflict = function () {
+ root.async = previous_async;
+ return async;
+ };
+
+ function only_once(fn) {
+ var called = false;
+ return function() {
+ if (called) throw new Error("Callback was already called.");
+ called = true;
+ fn.apply(root, arguments);
+ }
+ }
+
+ //// cross-browser compatiblity functions ////
+
+ var _toString = Object.prototype.toString;
+
+ var _isArray = Array.isArray || function (obj) {
+ return _toString.call(obj) === '[object Array]';
+ };
+
+ var _each = function (arr, iterator) {
+ if (arr.forEach) {
+ return arr.forEach(iterator);
+ }
+ for (var i = 0; i < arr.length; i += 1) {
+ iterator(arr[i], i, arr);
+ }
+ };
+
+ var _map = function (arr, iterator) {
+ if (arr.map) {
+ return arr.map(iterator);
+ }
+ var results = [];
+ _each(arr, function (x, i, a) {
+ results.push(iterator(x, i, a));
+ });
+ return results;
+ };
+
+ var _reduce = function (arr, iterator, memo) {
+ if (arr.reduce) {
+ return arr.reduce(iterator, memo);
+ }
+ _each(arr, function (x, i, a) {
+ memo = iterator(memo, x, i, a);
+ });
+ return memo;
+ };
+
+ var _keys = function (obj) {
+ if (Object.keys) {
+ return Object.keys(obj);
+ }
+ var keys = [];
+ for (var k in obj) {
+ if (obj.hasOwnProperty(k)) {
+ keys.push(k);
+ }
+ }
+ return keys;
+ };
+
+ //// exported async module functions ////
+
+ //// nextTick implementation with browser-compatible fallback ////
+ if (typeof process === 'undefined' || !(process.nextTick)) {
+ if (typeof setImmediate === 'function') {
+ async.nextTick = function (fn) {
+ // not a direct alias for IE10 compatibility
+ setImmediate(fn);
+ };
+ async.setImmediate = async.nextTick;
+ }
+ else {
+ async.nextTick = function (fn) {
+ setTimeout(fn, 0);
+ };
+ async.setImmediate = async.nextTick;
+ }
+ }
+ else {
+ async.nextTick = process.nextTick;
+ if (typeof setImmediate !== 'undefined') {
+ async.setImmediate = function (fn) {
+ // not a direct alias for IE10 compatibility
+ setImmediate(fn);
+ };
+ }
+ else {
+ async.setImmediate = async.nextTick;
+ }
+ }
+
+ async.each = function (arr, iterator, callback) {
+ callback = callback || function () {};
+ if (!arr.length) {
+ return callback();
+ }
+ var completed = 0;
+ _each(arr, function (x) {
+ iterator(x, only_once(done) );
+ });
+ function done(err) {
+ if (err) {
+ callback(err);
+ callback = function () {};
+ }
+ else {
+ completed += 1;
+ if (completed >= arr.length) {
+ callback();
+ }
+ }
+ }
+ };
+ async.forEach = async.each;
+
+ async.eachSeries = function (arr, iterator, callback) {
+ callback = callback || function () {};
+ if (!arr.length) {
+ return callback();
+ }
+ var completed = 0;
+ var iterate = function () {
+ iterator(arr[completed], function (err) {
+ if (err) {
+ callback(err);
+ callback = function () {};
+ }
+ else {
+ completed += 1;
+ if (completed >= arr.length) {
+ callback();
+ }
+ else {
+ iterate();
+ }
+ }
+ });
+ };
+ iterate();
+ };
+ async.forEachSeries = async.eachSeries;
+
+ async.eachLimit = function (arr, limit, iterator, callback) {
+ var fn = _eachLimit(limit);
+ fn.apply(null, [arr, iterator, callback]);
+ };
+ async.forEachLimit = async.eachLimit;
+
+ var _eachLimit = function (limit) {
+
+ return function (arr, iterator, callback) {
+ callback = callback || function () {};
+ if (!arr.length || limit <= 0) {
+ return callback();
+ }
+ var completed = 0;
+ var started = 0;
+ var running = 0;
+
+ (function replenish () {
+ if (completed >= arr.length) {
+ return callback();
+ }
+
+ while (running < limit && started < arr.length) {
+ started += 1;
+ running += 1;
+ iterator(arr[started - 1], function (err) {
+ if (err) {
+ callback(err);
+ callback = function () {};
+ }
+ else {
+ completed += 1;
+ running -= 1;
+ if (completed >= arr.length) {
+ callback();
+ }
+ else {
+ replenish();
+ }
+ }
+ });
+ }
+ })();
+ };
+ };
+
+
+ var doParallel = function (fn) {
+ return function () {
+ var args = Array.prototype.slice.call(arguments);
+ return fn.apply(null, [async.each].concat(args));
+ };
+ };
+ var doParallelLimit = function(limit, fn) {
+ return function () {
+ var args = Array.prototype.slice.call(arguments);
+ return fn.apply(null, [_eachLimit(limit)].concat(args));
+ };
+ };
+ var doSeries = function (fn) {
+ return function () {
+ var args = Array.prototype.slice.call(arguments);
+ return fn.apply(null, [async.eachSeries].concat(args));
+ };
+ };
+
+
+ var _asyncMap = function (eachfn, arr, iterator, callback) {
+ arr = _map(arr, function (x, i) {
+ return {index: i, value: x};
+ });
+ if (!callback) {
+ eachfn(arr, function (x, callback) {
+ iterator(x.value, function (err) {
+ callback(err);
+ });
+ });
+ } else {
+ var results = [];
+ eachfn(arr, function (x, callback) {
+ iterator(x.value, function (err, v) {
+ results[x.index] = v;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
+ }
+ };
+ async.map = doParallel(_asyncMap);
+ async.mapSeries = doSeries(_asyncMap);
+ async.mapLimit = function (arr, limit, iterator, callback) {
+ return _mapLimit(limit)(arr, iterator, callback);
+ };
+
+ var _mapLimit = function(limit) {
+ return doParallelLimit(limit, _asyncMap);
+ };
+
+ // reduce only has a series version, as doing reduce in parallel won't
+ // work in many situations.
+ async.reduce = function (arr, memo, iterator, callback) {
+ async.eachSeries(arr, function (x, callback) {
+ iterator(memo, x, function (err, v) {
+ memo = v;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, memo);
+ });
+ };
+ // inject alias
+ async.inject = async.reduce;
+ // foldl alias
+ async.foldl = async.reduce;
+
+ async.reduceRight = function (arr, memo, iterator, callback) {
+ var reversed = _map(arr, function (x) {
+ return x;
+ }).reverse();
+ async.reduce(reversed, memo, iterator, callback);
+ };
+ // foldr alias
+ async.foldr = async.reduceRight;
+
+ var _filter = function (eachfn, arr, iterator, callback) {
+ var results = [];
+ arr = _map(arr, function (x, i) {
+ return {index: i, value: x};
+ });
+ eachfn(arr, function (x, callback) {
+ iterator(x.value, function (v) {
+ if (v) {
+ results.push(x);
+ }
+ callback();
+ });
+ }, function (err) {
+ callback(_map(results.sort(function (a, b) {
+ return a.index - b.index;
+ }), function (x) {
+ return x.value;
+ }));
+ });
+ };
+ async.filter = doParallel(_filter);
+ async.filterSeries = doSeries(_filter);
+ // select alias
+ async.select = async.filter;
+ async.selectSeries = async.filterSeries;
+
+ var _reject = function (eachfn, arr, iterator, callback) {
+ var results = [];
+ arr = _map(arr, function (x, i) {
+ return {index: i, value: x};
+ });
+ eachfn(arr, function (x, callback) {
+ iterator(x.value, function (v) {
+ if (!v) {
+ results.push(x);
+ }
+ callback();
+ });
+ }, function (err) {
+ callback(_map(results.sort(function (a, b) {
+ return a.index - b.index;
+ }), function (x) {
+ return x.value;
+ }));
+ });
+ };
+ async.reject = doParallel(_reject);
+ async.rejectSeries = doSeries(_reject);
+
+ var _detect = function (eachfn, arr, iterator, main_callback) {
+ eachfn(arr, function (x, callback) {
+ iterator(x, function (result) {
+ if (result) {
+ main_callback(x);
+ main_callback = function () {};
+ }
+ else {
+ callback();
+ }
+ });
+ }, function (err) {
+ main_callback();
+ });
+ };
+ async.detect = doParallel(_detect);
+ async.detectSeries = doSeries(_detect);
+
+ async.some = function (arr, iterator, main_callback) {
+ async.each(arr, function (x, callback) {
+ iterator(x, function (v) {
+ if (v) {
+ main_callback(true);
+ main_callback = function () {};
+ }
+ callback();
+ });
+ }, function (err) {
+ main_callback(false);
+ });
+ };
+ // any alias
+ async.any = async.some;
+
+ async.every = function (arr, iterator, main_callback) {
+ async.each(arr, function (x, callback) {
+ iterator(x, function (v) {
+ if (!v) {
+ main_callback(false);
+ main_callback = function () {};
+ }
+ callback();
+ });
+ }, function (err) {
+ main_callback(true);
+ });
+ };
+ // all alias
+ async.all = async.every;
+
+ async.sortBy = function (arr, iterator, callback) {
+ async.map(arr, function (x, callback) {
+ iterator(x, function (err, criteria) {
+ if (err) {
+ callback(err);
+ }
+ else {
+ callback(null, {value: x, criteria: criteria});
+ }
+ });
+ }, function (err, results) {
+ if (err) {
+ return callback(err);
+ }
+ else {
+ var fn = function (left, right) {
+ var a = left.criteria, b = right.criteria;
+ return a < b ? -1 : a > b ? 1 : 0;
+ };
+ callback(null, _map(results.sort(fn), function (x) {
+ return x.value;
+ }));
+ }
+ });
+ };
+
+ async.auto = function (tasks, callback) {
+ callback = callback || function () {};
+ var keys = _keys(tasks);
+ var remainingTasks = keys.length
+ if (!remainingTasks) {
+ return callback();
+ }
+
+ var results = {};
+
+ var listeners = [];
+ var addListener = function (fn) {
+ listeners.unshift(fn);
+ };
+ var removeListener = function (fn) {
+ for (var i = 0; i < listeners.length; i += 1) {
+ if (listeners[i] === fn) {
+ listeners.splice(i, 1);
+ return;
+ }
+ }
+ };
+ var taskComplete = function () {
+ remainingTasks--
+ _each(listeners.slice(0), function (fn) {
+ fn();
+ });
+ };
+
+ addListener(function () {
+ if (!remainingTasks) {
+ var theCallback = callback;
+ // prevent final callback from calling itself if it errors
+ callback = function () {};
+
+ theCallback(null, results);
+ }
+ });
+
+ _each(keys, function (k) {
+ var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
+ var taskCallback = function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ if (err) {
+ var safeResults = {};
+ _each(_keys(results), function(rkey) {
+ safeResults[rkey] = results[rkey];
+ });
+ safeResults[k] = args;
+ callback(err, safeResults);
+ // stop subsequent errors hitting callback multiple times
+ callback = function () {};
+ }
+ else {
+ results[k] = args;
+ async.setImmediate(taskComplete);
+ }
+ };
+ var requires = task.slice(0, Math.abs(task.length - 1)) || [];
+ var ready = function () {
+ return _reduce(requires, function (a, x) {
+ return (a && results.hasOwnProperty(x));
+ }, true) && !results.hasOwnProperty(k);
+ };
+ if (ready()) {
+ task[task.length - 1](taskCallback, results);
+ }
+ else {
+ var listener = function () {
+ if (ready()) {
+ removeListener(listener);
+ task[task.length - 1](taskCallback, results);
+ }
+ };
+ addListener(listener);
+ }
+ });
+ };
+
+ async.retry = function(times, task, callback) {
+ var DEFAULT_TIMES = 5;
+ var attempts = [];
+ // Use defaults if times not passed
+ if (typeof times === 'function') {
+ callback = task;
+ task = times;
+ times = DEFAULT_TIMES;
+ }
+ // Make sure times is a number
+ times = parseInt(times, 10) || DEFAULT_TIMES;
+ var wrappedTask = function(wrappedCallback, wrappedResults) {
+ var retryAttempt = function(task, finalAttempt) {
+ return function(seriesCallback) {
+ task(function(err, result){
+ seriesCallback(!err || finalAttempt, {err: err, result: result});
+ }, wrappedResults);
+ };
+ };
+ while (times) {
+ attempts.push(retryAttempt(task, !(times-=1)));
+ }
+ async.series(attempts, function(done, data){
+ data = data[data.length - 1];
+ (wrappedCallback || callback)(data.err, data.result);
+ });
+ }
+ // If a callback is passed, run this as a controll flow
+ return callback ? wrappedTask() : wrappedTask
+ };
+
+ async.waterfall = function (tasks, callback) {
+ callback = callback || function () {};
+ if (!_isArray(tasks)) {
+ var err = new Error('First argument to waterfall must be an array of functions');
+ return callback(err);
+ }
+ if (!tasks.length) {
+ return callback();
+ }
+ var wrapIterator = function (iterator) {
+ return function (err) {
+ if (err) {
+ callback.apply(null, arguments);
+ callback = function () {};
+ }
+ else {
+ var args = Array.prototype.slice.call(arguments, 1);
+ var next = iterator.next();
+ if (next) {
+ args.push(wrapIterator(next));
+ }
+ else {
+ args.push(callback);
+ }
+ async.setImmediate(function () {
+ iterator.apply(null, args);
+ });
+ }
+ };
+ };
+ wrapIterator(async.iterator(tasks))();
+ };
+
+ var _parallel = function(eachfn, tasks, callback) {
+ callback = callback || function () {};
+ if (_isArray(tasks)) {
+ eachfn.map(tasks, function (fn, callback) {
+ if (fn) {
+ fn(function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ callback.call(null, err, args);
+ });
+ }
+ }, callback);
+ }
+ else {
+ var results = {};
+ eachfn.each(_keys(tasks), function (k, callback) {
+ tasks[k](function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ results[k] = args;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
+ }
+ };
+
+ async.parallel = function (tasks, callback) {
+ _parallel({ map: async.map, each: async.each }, tasks, callback);
+ };
+
+ async.parallelLimit = function(tasks, limit, callback) {
+ _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
+ };
+
+ async.series = function (tasks, callback) {
+ callback = callback || function () {};
+ if (_isArray(tasks)) {
+ async.mapSeries(tasks, function (fn, callback) {
+ if (fn) {
+ fn(function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ callback.call(null, err, args);
+ });
+ }
+ }, callback);
+ }
+ else {
+ var results = {};
+ async.eachSeries(_keys(tasks), function (k, callback) {
+ tasks[k](function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ results[k] = args;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
+ }
+ };
+
+ async.iterator = function (tasks) {
+ var makeCallback = function (index) {
+ var fn = function () {
+ if (tasks.length) {
+ tasks[index].apply(null, arguments);
+ }
+ return fn.next();
+ };
+ fn.next = function () {
+ return (index < tasks.length - 1) ? makeCallback(index + 1): null;
+ };
+ return fn;
+ };
+ return makeCallback(0);
+ };
+
+ async.apply = function (fn) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function () {
+ return fn.apply(
+ null, args.concat(Array.prototype.slice.call(arguments))
+ );
+ };
+ };
+
+ var _concat = function (eachfn, arr, fn, callback) {
+ var r = [];
+ eachfn(arr, function (x, cb) {
+ fn(x, function (err, y) {
+ r = r.concat(y || []);
+ cb(err);
+ });
+ }, function (err) {
+ callback(err, r);
+ });
+ };
+ async.concat = doParallel(_concat);
+ async.concatSeries = doSeries(_concat);
+
+ async.whilst = function (test, iterator, callback) {
+ if (test()) {
+ iterator(function (err) {
+ if (err) {
+ return callback(err);
+ }
+ async.whilst(test, iterator, callback);
+ });
+ }
+ else {
+ callback();
+ }
+ };
+
+ async.doWhilst = function (iterator, test, callback) {
+ iterator(function (err) {
+ if (err) {
+ return callback(err);
+ }
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (test.apply(null, args)) {
+ async.doWhilst(iterator, test, callback);
+ }
+ else {
+ callback();
+ }
+ });
+ };
+
+ async.until = function (test, iterator, callback) {
+ if (!test()) {
+ iterator(function (err) {
+ if (err) {
+ return callback(err);
+ }
+ async.until(test, iterator, callback);
+ });
+ }
+ else {
+ callback();
+ }
+ };
+
+ async.doUntil = function (iterator, test, callback) {
+ iterator(function (err) {
+ if (err) {
+ return callback(err);
+ }
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (!test.apply(null, args)) {
+ async.doUntil(iterator, test, callback);
+ }
+ else {
+ callback();
+ }
+ });
+ };
+
+ async.queue = function (worker, concurrency) {
+ if (concurrency === undefined) {
+ concurrency = 1;
+ }
+ function _insert(q, data, pos, callback) {
+ if (!q.started){
+ q.started = true;
+ }
+ if (!_isArray(data)) {
+ data = [data];
+ }
+ if(data.length == 0) {
+ // call drain immediately if there are no tasks
+ return async.setImmediate(function() {
+ if (q.drain) {
+ q.drain();
+ }
+ });
+ }
+ _each(data, function(task) {
+ var item = {
+ data: task,
+ callback: typeof callback === 'function' ? callback : null
+ };
+
+ if (pos) {
+ q.tasks.unshift(item);
+ } else {
+ q.tasks.push(item);
+ }
+
+ if (q.saturated && q.tasks.length === q.concurrency) {
+ q.saturated();
+ }
+ async.setImmediate(q.process);
+ });
+ }
+
+ var workers = 0;
+ var q = {
+ tasks: [],
+ concurrency: concurrency,
+ saturated: null,
+ empty: null,
+ drain: null,
+ started: false,
+ paused: false,
+ push: function (data, callback) {
+ _insert(q, data, false, callback);
+ },
+ kill: function () {
+ q.drain = null;
+ q.tasks = [];
+ },
+ unshift: function (data, callback) {
+ _insert(q, data, true, callback);
+ },
+ process: function () {
+ if (!q.paused && workers < q.concurrency && q.tasks.length) {
+ var task = q.tasks.shift();
+ if (q.empty && q.tasks.length === 0) {
+ q.empty();
+ }
+ workers += 1;
+ var next = function () {
+ workers -= 1;
+ if (task.callback) {
+ task.callback.apply(task, arguments);
+ }
+ if (q.drain && q.tasks.length + workers === 0) {
+ q.drain();
+ }
+ q.process();
+ };
+ var cb = only_once(next);
+ worker(task.data, cb);
+ }
+ },
+ length: function () {
+ return q.tasks.length;
+ },
+ running: function () {
+ return workers;
+ },
+ idle: function() {
+ return q.tasks.length + workers === 0;
+ },
+ pause: function () {
+ if (q.paused === true) { return; }
+ q.paused = true;
+ q.process();
+ },
+ resume: function () {
+ if (q.paused === false) { return; }
+ q.paused = false;
+ q.process();
+ }
+ };
+ return q;
+ };
+
+ async.priorityQueue = function (worker, concurrency) {
+
+ function _compareTasks(a, b){
+ return a.priority - b.priority;
+ };
+
+ function _binarySearch(sequence, item, compare) {
+ var beg = -1,
+ end = sequence.length - 1;
+ while (beg < end) {
+ var mid = beg + ((end - beg + 1) >>> 1);
+ if (compare(item, sequence[mid]) >= 0) {
+ beg = mid;
+ } else {
+ end = mid - 1;
+ }
+ }
+ return beg;
+ }
+
+ function _insert(q, data, priority, callback) {
+ if (!q.started){
+ q.started = true;
+ }
+ if (!_isArray(data)) {
+ data = [data];
+ }
+ if(data.length == 0) {
+ // call drain immediately if there are no tasks
+ return async.setImmediate(function() {
+ if (q.drain) {
+ q.drain();
+ }
+ });
+ }
+ _each(data, function(task) {
+ var item = {
+ data: task,
+ priority: priority,
+ callback: typeof callback === 'function' ? callback : null
+ };
+
+ q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
+
+ if (q.saturated && q.tasks.length === q.concurrency) {
+ q.saturated();
+ }
+ async.setImmediate(q.process);
+ });
+ }
+
+ // Start with a normal queue
+ var q = async.queue(worker, concurrency);
+
+ // Override push to accept second parameter representing priority
+ q.push = function (data, priority, callback) {
+ _insert(q, data, priority, callback);
+ };
+
+ // Remove unshift function
+ delete q.unshift;
+
+ return q;
+ };
+
+ async.cargo = function (worker, payload) {
+ var working = false,
+ tasks = [];
+
+ var cargo = {
+ tasks: tasks,
+ payload: payload,
+ saturated: null,
+ empty: null,
+ drain: null,
+ drained: true,
+ push: function (data, callback) {
+ if (!_isArray(data)) {
+ data = [data];
+ }
+ _each(data, function(task) {
+ tasks.push({
+ data: task,
+ callback: typeof callback === 'function' ? callback : null
+ });
+ cargo.drained = false;
+ if (cargo.saturated && tasks.length === payload) {
+ cargo.saturated();
+ }
+ });
+ async.setImmediate(cargo.process);
+ },
+ process: function process() {
+ if (working) return;
+ if (tasks.length === 0) {
+ if(cargo.drain && !cargo.drained) cargo.drain();
+ cargo.drained = true;
+ return;
+ }
+
+ var ts = typeof payload === 'number'
+ ? tasks.splice(0, payload)
+ : tasks.splice(0, tasks.length);
+
+ var ds = _map(ts, function (task) {
+ return task.data;
+ });
+
+ if(cargo.empty) cargo.empty();
+ working = true;
+ worker(ds, function () {
+ working = false;
+
+ var args = arguments;
+ _each(ts, function (data) {
+ if (data.callback) {
+ data.callback.apply(null, args);
+ }
+ });
+
+ process();
+ });
+ },
+ length: function () {
+ return tasks.length;
+ },
+ running: function () {
+ return working;
+ }
+ };
+ return cargo;
+ };
+
+ var _console_fn = function (name) {
+ return function (fn) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ fn.apply(null, args.concat([function (err) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ if (typeof console !== 'undefined') {
+ if (err) {
+ if (console.error) {
+ console.error(err);
+ }
+ }
+ else if (console[name]) {
+ _each(args, function (x) {
+ console[name](x);
+ });
+ }
+ }
+ }]));
+ };
+ };
+ async.log = _console_fn('log');
+ async.dir = _console_fn('dir');
+ /*async.info = _console_fn('info');
+ async.warn = _console_fn('warn');
+ async.error = _console_fn('error');*/
+
+ async.memoize = function (fn, hasher) {
+ var memo = {};
+ var queues = {};
+ hasher = hasher || function (x) {
+ return x;
+ };
+ var memoized = function () {
+ var args = Array.prototype.slice.call(arguments);
+ var callback = args.pop();
+ var key = hasher.apply(null, args);
+ if (key in memo) {
+ async.nextTick(function () {
+ callback.apply(null, memo[key]);
+ });
+ }
+ else if (key in queues) {
+ queues[key].push(callback);
+ }
+ else {
+ queues[key] = [callback];
+ fn.apply(null, args.concat([function () {
+ memo[key] = arguments;
+ var q = queues[key];
+ delete queues[key];
+ for (var i = 0, l = q.length; i < l; i++) {
+ q[i].apply(null, arguments);
+ }
+ }]));
+ }
+ };
+ memoized.memo = memo;
+ memoized.unmemoized = fn;
+ return memoized;
+ };
+
+ async.unmemoize = function (fn) {
+ return function () {
+ return (fn.unmemoized || fn).apply(null, arguments);
+ };
+ };
+
+ async.times = function (count, iterator, callback) {
+ var counter = [];
+ for (var i = 0; i < count; i++) {
+ counter.push(i);
+ }
+ return async.map(counter, iterator, callback);
+ };
+
+ async.timesSeries = function (count, iterator, callback) {
+ var counter = [];
+ for (var i = 0; i < count; i++) {
+ counter.push(i);
+ }
+ return async.mapSeries(counter, iterator, callback);
+ };
+
+ async.seq = function (/* functions... */) {
+ var fns = arguments;
+ return function () {
+ var that = this;
+ var args = Array.prototype.slice.call(arguments);
+ var callback = args.pop();
+ async.reduce(fns, args, function (newargs, fn, cb) {
+ fn.apply(that, newargs.concat([function () {
+ var err = arguments[0];
+ var nextargs = Array.prototype.slice.call(arguments, 1);
+ cb(err, nextargs);
+ }]))
+ },
+ function (err, results) {
+ callback.apply(that, [err].concat(results));
+ });
+ };
+ };
+
+ async.compose = function (/* functions... */) {
+ return async.seq.apply(null, Array.prototype.reverse.call(arguments));
+ };
+
+ var _applyEach = function (eachfn, fns /*args...*/) {
+ var go = function () {
+ var that = this;
+ var args = Array.prototype.slice.call(arguments);
+ var callback = args.pop();
+ return eachfn(fns, function (fn, cb) {
+ fn.apply(that, args.concat([cb]));
+ },
+ callback);
+ };
+ if (arguments.length > 2) {
+ var args = Array.prototype.slice.call(arguments, 2);
+ return go.apply(this, args);
+ }
+ else {
+ return go;
+ }
+ };
+ async.applyEach = doParallel(_applyEach);
+ async.applyEachSeries = doSeries(_applyEach);
+
+ async.forever = function (fn, callback) {
+ function next(err) {
+ if (err) {
+ if (callback) {
+ return callback(err);
+ }
+ throw err;
+ }
+ fn(next);
+ }
+ next();
+ };
+
+ // Node.js
+ if (typeof module !== 'undefined' && module.exports) {
+ module.exports = async;
+ }
+ // AMD / RequireJS
+ else if (typeof define !== 'undefined' && define.amd) {
+ define([], function () {
+ return async;
+ });
+ }
+ // included directly via