From 3adfd45cb63eec87469586beafc627540234e4a4 Mon Sep 17 00:00:00 2001
From: Rob Eisenberg <rob@bluespire.com>
Date: Fri, 15 Jul 2016 10:44:10 -0400
Subject: [PATCH] feat(bundling): enable dependencies to include additional
 resources

---
 ACKNOWLEDGEMENTS.md                  |  27 +++++
 lib/build/bundled-source.js          |   2 +-
 lib/build/dependency-inclusion.js    |  14 +++
 lib/build/map-stream/index.js        | 141 +++++++++++++++++++++++++++
 lib/build/source-inclusion.js        |  21 ++++
 lib/commands/new/project-template.js |   5 +-
 lib/dependencies.js                  |   3 +-
 7 files changed, 209 insertions(+), 4 deletions(-)
 create mode 100644 lib/build/map-stream/index.js

diff --git a/ACKNOWLEDGEMENTS.md b/ACKNOWLEDGEMENTS.md
index 67cb7a581..7b982bb8e 100644
--- a/ACKNOWLEDGEMENTS.md
+++ b/ACKNOWLEDGEMENTS.md
@@ -162,3 +162,30 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
+
+## map-stream (embedded)
+
+The MIT License (MIT)
+
+Copyright (c) 2011 Dominic Tarr
+
+Permission is hereby granted, free of charge,
+to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to
+deal in the Software without restriction, including
+without limitation the rights to use, copy, modify,
+merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom
+the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/lib/build/bundled-source.js b/lib/build/bundled-source.js
index 87f741857..27e643fe8 100644
--- a/lib/build/bundled-source.js
+++ b/lib/build/bundled-source.js
@@ -50,7 +50,7 @@ exports.BundledSource = class {
     let loaderConfig = bundler.loaderConfig;
     let loaderPlugins = bundler.loaderOptions.plugins;
     let rootDir = process.cwd();
-    let moduleId = this.moduleId = this.calculateModuleId(rootDir, loaderConfig);
+    let moduleId = this.moduleId || (this.moduleId = this.calculateModuleId(rootDir, loaderConfig));
     let that = this;
 
     console.log(`Tracing ${moduleId}...`);
diff --git a/lib/build/dependency-inclusion.js b/lib/build/dependency-inclusion.js
index 8d7d2811e..186094091 100644
--- a/lib/build/dependency-inclusion.js
+++ b/lib/build/dependency-inclusion.js
@@ -1,5 +1,7 @@
 "use strict";
 const os = require('os');
+const path = require('path');
+const SourceInclusion = require('./source-inclusion').SourceInclusion;
 
 exports.DependencyInclusion = class {
   constructor(bundle, description) {
@@ -8,6 +10,18 @@ exports.DependencyInclusion = class {
     this.items = [];
     this.traceDependencies = true;
     bundle.bundler.addFile(new DependencyFile(bundle, description), this);
+
+    let loaderConfig = description.loaderConfig;
+    let resources = loaderConfig.resources;
+
+    if (resources) {
+      resources.forEach(x => {
+        let pattern = path.join(loaderConfig.path, x);
+        let inclusion = new SourceInclusion(bundle, pattern);
+        inclusion.addAllMatchingResources(loaderConfig);
+        bundle.includes.push(inclusion);
+      });
+    }
   }
 
   addItem(item) {
diff --git a/lib/build/map-stream/index.js b/lib/build/map-stream/index.js
new file mode 100644
index 000000000..7a7c2a389
--- /dev/null
+++ b/lib/build/map-stream/index.js
@@ -0,0 +1,141 @@
+//filter will reemit the data if cb(err,pass) pass is truthy
+
+// reduce is more tricky
+// maybe we want to group the reductions or emit progress updates occasionally
+// the most basic reduce just emits one 'data' event after it has recieved 'end'
+
+
+var Stream = require('stream').Stream
+
+
+//create an event stream and apply function to each .write
+//emitting each response as data
+//unless it's an empty callback
+
+module.exports = function (mapper, opts) {
+
+  var stream = new Stream()
+    , self = this
+    , inputs = 0
+    , outputs = 0
+    , ended = false
+    , paused = false
+    , destroyed = false
+    , lastWritten = 0
+    , inNext = false
+
+  this.opts = opts || {};
+  var errorEventName = this.opts.failures ? 'failure' : 'error';
+
+  // Items that are not ready to be written yet (because they would come out of
+  // order) get stuck in a queue for later.
+  var writeQueue = {}
+
+  stream.writable = true
+  stream.readable = true
+
+  function queueData (data, number) {
+    var nextToWrite = lastWritten + 1
+
+    if (number === nextToWrite) {
+      // If it's next, and its not undefined write it
+      if (data !== undefined) {
+        stream.emit.apply(stream, ['data', data])
+      }
+      lastWritten ++
+      nextToWrite ++
+    } else {
+      // Otherwise queue it for later.
+      writeQueue[number] = data
+    }
+
+    // If the next value is in the queue, write it
+    if (writeQueue.hasOwnProperty(nextToWrite)) {
+      var dataToWrite = writeQueue[nextToWrite]
+      delete writeQueue[nextToWrite]
+      return queueData(dataToWrite, nextToWrite)
+    }
+
+    outputs ++
+    if(inputs === outputs) {
+      if(paused) paused = false, stream.emit('drain') //written all the incoming events
+      if(ended) end()
+    }
+  }
+
+  function next (err, data, number) {
+    if(destroyed) return
+    inNext = true
+
+    if (!err || self.opts.failures) {
+      queueData(data, number)
+    }
+
+    if (err) {
+      stream.emit.apply(stream, [ errorEventName, err ]);
+    }
+
+    inNext = false;
+  }
+
+  // Wrap the mapper function by calling its callback with the order number of
+  // the item in the stream.
+  function wrappedMapper (input, number, callback) {
+    return mapper.call(null, input, function(err, data){
+      callback(err, data, number)
+    })
+  }
+
+  stream.write = function (data) {
+    if(ended) throw new Error('map stream is not writable')
+    inNext = false
+    inputs ++
+
+    try {
+      //catch sync errors and handle them like async errors
+      var written = wrappedMapper(data, inputs, next)
+      paused = (written === false)
+      return !paused
+    } catch (err) {
+      //if the callback has been called syncronously, and the error
+      //has occured in an listener, throw it again.
+      if(inNext)
+        throw err
+      next(err)
+      return !paused
+    }
+  }
+
+  function end (data) {
+    //if end was called with args, write it,
+    ended = true //write will emit 'end' if ended is true
+    stream.writable = false
+    if(data !== undefined) {
+      return queueData(data, inputs)
+    } else if (inputs == outputs) { //wait for processing
+      stream.readable = false, stream.emit('end'), stream.destroy()
+    }
+  }
+
+  stream.end = function (data) {
+    if(ended) return
+    end(data)
+  }
+
+  stream.destroy = function () {
+    ended = destroyed = true
+    stream.writable = stream.readable = paused = false
+    process.nextTick(function () {
+      stream.emit('close')
+    })
+  }
+  stream.pause = function () {
+    paused = true
+  }
+
+  stream.resume = function () {
+    paused = false
+  }
+
+  return stream
+}
diff --git a/lib/build/source-inclusion.js b/lib/build/source-inclusion.js
index c1e250443..5c972db75 100644
--- a/lib/build/source-inclusion.js
+++ b/lib/build/source-inclusion.js
@@ -1,5 +1,9 @@
 "use strict";
 const os = require("os");
+const path = require("path");
+const vfs = require('vinyl-fs');
+const mapStream = require('./map-stream');
+const BundledSource = require('./bundled-source').BundledSource;
 
 exports.SourceInclusion = class {
   constructor(bundle, pattern) {
@@ -35,6 +39,23 @@ exports.SourceInclusion = class {
     return false;
   }
 
+  addAllMatchingResources(loaderConfig) {
+    let bundler = this.bundle.bundler;
+    let root = path.resolve(bundler.project.paths.root, loaderConfig.path);
+    let pattern = path.resolve(bundler.project.paths.root, this.pattern);
+
+    var subsume = (file, cb) => {
+      let moduleId = path.join(loaderConfig.name, file.path.replace(root, ''));
+      let ext = path.extname(moduleId);
+      let item = new BundledSource(bundler, file);
+      item.moduleId = moduleId.substring(0, moduleId.length - ext.length);
+      this.addItem(item);
+      cb(null, file);
+    };
+
+    vfs.src(pattern).pipe(mapStream(subsume));
+  }
+
   transform() {
     let index = -1;
     let items = this.items;
diff --git a/lib/commands/new/project-template.js b/lib/commands/new/project-template.js
index f68f7cc6e..b2cd67859 100644
--- a/lib/commands/new/project-template.js
+++ b/lib/commands/new/project-template.js
@@ -155,9 +155,10 @@ exports.ProjectTemplate = class {
       'gulp-rename',
       'gulp-sourcemaps',
       'gulp-notify',
-      'uglify-js',
       'minimatch',
-      'through2'
+      'through2',
+      'uglify-js',
+      'vinyl-fs'
     );
   }
 
diff --git a/lib/dependencies.js b/lib/dependencies.js
index b05ef388c..a21986f18 100644
--- a/lib/dependencies.js
+++ b/lib/dependencies.js
@@ -48,7 +48,8 @@ let versionMap = {
   "tslint": "^3.11.0",
   "typings": "^1.3.0",
   "typescript": ">=1.9.0-dev || ^2.0.0",
-  "uglify-js": "^2.6.3"
+  "uglify-js": "^2.6.3",
+  "vinyl-fs": "^2.4.3"
 };
 
 exports.getSupportedVersion = function(name) {