<commit_before>var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;

var browserResolve = require('browser-resolve');
var nodeResolve = require('resolve');
var detective = require('detective');
var through = require('through2');
var concat = require('concat-stream');
var parents = require('parents');
var combine = require('stream-combiner2');
var duplexer = require('duplexer2');
var copy = require('shallow-copy');

var inherits = require('inherits');
var Transform = require('readable-stream').Transform;

module.exports = Deps;
inherits(Deps, Transform);

function Deps (opts) {
    var self = this;
    if (!(this instanceof Deps)) return new Deps(opts);
    Transform.call(this, { objectMode: true });

    if (!opts) opts = {};

    this.basedir = opts.basedir || process.cwd();
    this.cache = opts.cache;
    this.pkgCache = opts.packageCache || {};
    this.pkgFileCache = {};
    this.pkgFileCachePending = {};
    this.visited = {};
    this.walking = {};
    this.entries = [];

    this.paths = opts.paths || process.env.NODE_PATH;
    if (typeof this.paths === 'string') {
        this.paths = process.env.NODE_PATH.split(':');
    }
    if (!this.paths) this.paths = [];

    this.transforms = [].concat(opts.transform).filter(Boolean);
    this.globalTransforms = [].concat(opts.globalTransform).filter(Boolean);
    this.resolver = opts.resolve || browserResolve;
    this.options = opts;
    this.pending = 0;

    var topfile = path.join(this.basedir, '__fake.js');
    this.top = { id: topfile, filename: topfile, paths: this.paths };
}

Deps.prototype._transform = function (row, enc, next) {
    var self = this;
    self.pending ++;
    if (typeof row === 'string') {
        row = { file: row };
    }
    if (row.entry !== false) self.entries.push(row.file);

    self.lookupPackage(row.file, function (err, pkg) {
        if (err && this.options.ignoreMissing) {
            self.emit('missing', row.file, self.top);
            self.pending --;
            return next();
        }
        if (err) return self.emit('error', err)
        self.pending --;
        start(pkg)
    });
    next();

    function start (pkg) {
        if (!pkg) pkg = {};
        if (!pkg.__dirname) pkg.__dirname = path.dirname(row.file);
        self.walk(row, self.top);
    }
};

Deps.prototype._flush = function () {
    if (this.pending === 0) this.push(null);
    this._ended = true;
};

Deps.prototype.resolve = function (id, parent, cb) {
    var self = this;
    var opts = self.options;

    if (xhas(self.cache, parent.id, 'deps', id)
    && self.cache[parent.id].deps) {
        var file = self.cache[parent.id].deps[id];
        var pkg = self.pkgCache[file];
        if (pkg) return cb(null, file, pkg);
        return self.lookupPackage(file, function (err, pkg) {
            cb(null, file, pkg);
        });
    }

    var pkgdir;
    parent.packageFilter = function (p, x) {
        pkgdir = x;
        if (opts.packageFilter) return opts.packageFilter(p, x);
        else return p;
    };

    if (opts.extensions) parent.extensions = opts.extensions;
    if (opts.modules) parent.modules = opts.modules;

    self.resolver(id, parent, function onresolve (err, file, pkg) {
        if (err) return cb(err);
        if (!file) return cb(new Error(
            'module not found: "' + id + '" from file '
            + parent.filename
        ));

        if (pkg && pkgdir) pkg.__dirname = pkgdir;
        if (!pkg || !pkg.__dirname) {
            self.lookupPackage(file, function (err, p) {
                if (err) return cb(err);
                if (!p) p = {};
                if (!p.__dirname) p.__dirname = path.dirname(file);
                self.pkgCache[file] = p;
                onresolve(err, file, opts.packageFilter
                    ? opts.packageFilter(p, p.__dirname) : p
                );
            });
        }
        else cb(err, file, pkg);
    });
};

Deps.prototype.readFile = function (file, id, pkg) {
    var tr = through();
    if (this.cache && this.cache[file]) {
        tr.push(this.cache[file].source);
        tr.push(null);
        return tr;
    }
    var rs = fs.createReadStream(file);
    rs.on('error', function (err) { tr.emit('error', err) });
    this.emit('file', file, id);
    return rs.pipe(this.getTransforms(file, pkg));
};

Deps.prototype.getTransforms = function (file, pkg) {
    var self = this;
    var isTopLevel = this.entries.some(function (main) {
        var m = path.relative(path.dirname(main), file);
        return m.split(/[\\\/]/).indexOf('node_modules') < 0;
    });

    var transforms = [].concat(isTopLevel ? this.transforms : [])
        .concat(getTransforms(pkg, {
            globalTransform: this.globalTransforms,
            transformKey: this.options.transformKey
        }))
    ;
    if (transforms.length === 0) return through();

    var pending = transforms.length;
    var streams = [];
    var input = through();
    var output = through();
    var dup = duplexer(input, output);

    for (var i = 0; i < transforms.length; i++) (function (i) {
        makeTransform(transforms[i], function (err, trs) {
            if (err) return self.emit('error', err)
            streams[i] = trs;
            if (-- pending === 0) done();
        });
    })(i);
    return dup;

    function done () {
        var middle = combine.apply(null, streams);
        middle.on('error', function (err) {
            self.emit('error', err);
        });
        input.pipe(middle).pipe(output);
    }

    function makeTransform (tr, cb) {
        var trOpts = {};
        if (Array.isArray(tr)) {
            trOpts = tr[1];
            tr = tr[0];
        }
        if (typeof tr === 'function') {
            var t = tr(file, trOpts);
            self.emit('transform', t, file);
            nextTick(cb, null, wrapTransform(t));
        }
        else {
            loadTransform(tr, trOpts, function (err, trs) {
                if (err) return cb(err);
                cb(null, wrapTransform(trs));
            });
        }
    }

    function loadTransform (id, trOpts, cb) {
        var params = { basedir: path.dirname(file) };
        nodeResolve(id, params, function nr (err, res, again) {
            if (err && again) return cb(err);

            if (err) {
                params.basedir = pkg.__dirname;
                return nodeResolve(id, params, function (e, r) {
                    nr(e, r, true)
                });
            }

            if (!res) return cb(new Error(
                'cannot find transform module ' + tr
                + ' while transforming ' + file
            ));

            var r = require(res);
            if (typeof r !== 'function') {
                return cb(new Error('transform not a function'));
            }

            var trs = r(file, trOpts);
            self.emit('transform', trs, file);
            cb(null, trs);
        });
    }
};

Deps.prototype.walk = function (id, parent, cb) {
    var self = this;
    var opts = self.options;
    this.pending ++;

    var rec = {};
    if (typeof id === 'object') {
        rec = copy(id);
        if (rec.entry === false) delete rec.entry;
        id = rec.file || rec.id;
    }

    self.resolve(id, parent, function (err, file, pkg) {
        if (rec.expose) {
            self.options.modules[rec.expose] = file;
        }

        if (opts.postFilter && !opts.postFilter(id, file, pkg)) {
            if (--self.pending === 0) self.push(null);
            return cb(null, undefined);
        }
        if (err && rec.source) {
            file = rec.file;

            var ts = self.getTransforms(file, pkg);
            ts.pipe(concat(function (body) {
                rec.source = body.toString('utf8');
                fromSource(rec.source);
            }));
            return ts.end(rec.source);
        }
        if (err && self.options.ignoreMissing) {
            if (--self.pending === 0) self.push(null);
            self.emit('missing', id, parent);
            return cb(null, undefined);
        }
        if (err) return self.emit('error', err);
        if (self.visited[file]) {
            if (-- self.pending === 0) self.push(null);
            return cb && cb(null, file);
        }
        self.visited[file] = true;

        if (rec.source) {
            var ts = self.getTransforms(file, pkg);
            ts.pipe(concat(function (body) {
                rec.source = body.toString('utf8');
                fromSource(rec.source);
            }));
            return ts.end(rec.source);
        }

        var c = self.cache && self.cache[file];
        if (c) return fromDeps(file, c.source, c.package, Object.keys(c.deps));

        self.readFile(file, id, pkg).pipe(concat(function (body) {
            fromSource(body.toString('utf8'));
        }));

        function fromSource (src) {
            var deps = self.parseDeps(file, src);
            if (deps) fromDeps(file, src, pkg, deps);
        }
    });

    function fromDeps (file, src, pkg, deps) {
        var p = deps.length;
        var current = {
            id: file,
            filename: file,
            paths: self.paths,
            package: pkg
        };
        var resolved = {};

        deps.forEach(function (id) {
            if (opts.filter && !opts.filter(id)) {
                resolved[id] = false;
                if (--p === 0) done();
                return;
            }
            self.walk(id, current, function (err, r) {
                resolved[id] = r;
                if (--p === 0) done();
            });
        });
        if (deps.length === 0) done();

        function done () {
            if (!rec.id) rec.id = file;
            if (!rec.source) rec.source = src;
            if (!rec.deps) rec.deps = resolved;
            if (!rec.file) rec.file = file;

            if (self.entries.indexOf(file) >= 0) {
                rec.entry = true;
            }
            self.push(rec);

            if (cb) cb(null, file);
            if (-- self.pending === 0 && self._ended) self.push(null);
        }
    }
};

Deps.prototype.parseDeps = function (file, src, cb) {
    if (this.options.noParse === true) return [];
    if (/\.json$/.test(file)) return [];

    if (Array.isArray(this.options.noParse)
    && this.options.noParse.indexOf(file) >= 0) {
        return [];
    }

    try { var deps = detective(src) }
    catch (ex) {
        var message = ex && ex.message ? ex.message : ex;
        this.emit('error', new Error(
            'Parsing file ' + file + ': ' + message
        ));
        return;
    }
    return deps;
};

Deps.prototype.lookupPackage = function (file, cb) {
    var self = this;

    var cached = this.pkgCache[file];
    if (cached) return nextTick(cb, null, cached);
    if (cached === false) return nextTick(cb, null, undefined);

    var dirs = parents(path.dirname(file));

    (function next () {
        if (dirs.length === 0) {
            self.pkgCache[file] = false;
            return cb(null, undefined);
        }
        var dir = dirs.shift();
        if (dir.split(/[\\\/]/).slice(-1)[0] === 'node_modules') {
            return cb(null, undefined);
        }

        var pkgfile = path.join(dir, 'package.json');

        var cached = self.pkgCache[pkgfile];
        if (cached) return nextTick(cb, null, cached);
        else if (cached === false) return next();

        var pcached = self.pkgFileCachePending[pkgfile];
        if (pcached) return pcached.push(onpkg);
        pcached = self.pkgFileCachePending[pkgfile] = [];

        fs.readFile(pkgfile, function (err, src) {
            if (err) return onpkg();
            try { var pkg = JSON.parse(src) }
            catch (err) {
                return onpkg(new Error([
                    err + ' while parsing json file ' + pkgfile
                ].join('')))
            }
            pkg.__dirname = dir;

            self.pkgCache[pkgfile] = pkg;
            self.pkgCache[file] = pkg;
            onpkg(null, pkg);
        });

        function onpkg (err, pkg) {
            if (self.pkgFileCachePending[pkgfile]) {
                var fns = self.pkgFileCachePending[pkgfile];
                delete self.pkgFileCachePending[pkgfile];
                fns.forEach(function (f) { f(err, pkg) });
            }
            if (err) cb(err)
            else if (pkg) cb(null, pkg)
            else {
                self.pkgCache[pkgfile] = false;
                next();
            }
        }
    })();
};

function getTransforms (pkg, opts) {
    var trx = [];
    if (opts.transformKey) {
        var n = pkg;
        var keys = opts.transformKey;
        for (var i = 0; i < keys.length; i++) {
            if (n && typeof n === 'object') n = n[keys[i]];
            else break;
        }
        if (i === keys.length) {
            trx = [].concat(n).filter(Boolean);
        }
    }
    return trx.concat(opts.globalTransform || []);
}

function nextTick (cb) {
    var args = [].slice.call(arguments, 1);
    process.nextTick(function () { cb.apply(null, args) });
}

function xhas (obj) {
    if (!obj) return false;
    for (var i = 1; i < arguments.length; i++) {
        var key = arguments[i];
        if (!has(obj, key)) return false;
        obj = obj[key];
    }
    return true;
}

function has (obj, key) {
    return Object.prototype.hasOwnProperty.call(obj, key);
}

function wrapTransform (tr) {
    if (typeof tr.read === 'function') return tr;
    var input = through(), output = through();
    input.pipe(tr).pipe(output);
    var wrapper = duplexer(input, output);
    tr.on('error', function (err) { wrapper.emit('error', err) });
    return wrapper;
}
<commit_msg>expose transform error filename<commit_after>var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;

var browserResolve = require('browser-resolve');
var nodeResolve = require('resolve');
var detective = require('detective');
var through = require('through2');
var concat = require('concat-stream');
var parents = require('parents');
var combine = require('stream-combiner2');
var duplexer = require('duplexer2');
var copy = require('shallow-copy');

var inherits = require('inherits');
var Transform = require('readable-stream').Transform;

module.exports = Deps;
inherits(Deps, Transform);

function Deps (opts) {
    var self = this;
    if (!(this instanceof Deps)) return new Deps(opts);
    Transform.call(this, { objectMode: true });

    if (!opts) opts = {};

    this.basedir = opts.basedir || process.cwd();
    this.cache = opts.cache;
    this.pkgCache = opts.packageCache || {};
    this.pkgFileCache = {};
    this.pkgFileCachePending = {};
    this.visited = {};
    this.walking = {};
    this.entries = [];

    this.paths = opts.paths || process.env.NODE_PATH;
    if (typeof this.paths === 'string') {
        this.paths = process.env.NODE_PATH.split(':');
    }
    if (!this.paths) this.paths = [];

    this.transforms = [].concat(opts.transform).filter(Boolean);
    this.globalTransforms = [].concat(opts.globalTransform).filter(Boolean);
    this.resolver = opts.resolve || browserResolve;
    this.options = opts;
    this.pending = 0;

    var topfile = path.join(this.basedir, '__fake.js');
    this.top = { id: topfile, filename: topfile, paths: this.paths };
}

Deps.prototype._transform = function (row, enc, next) {
    var self = this;
    self.pending ++;
    if (typeof row === 'string') {
        row = { file: row };
    }
    if (row.entry !== false) self.entries.push(row.file);

    self.lookupPackage(row.file, function (err, pkg) {
        if (err && this.options.ignoreMissing) {
            self.emit('missing', row.file, self.top);
            self.pending --;
            return next();
        }
        if (err) return self.emit('error', err)
        self.pending --;
        start(pkg)
    });
    next();

    function start (pkg) {
        if (!pkg) pkg = {};
        if (!pkg.__dirname) pkg.__dirname = path.dirname(row.file);
        self.walk(row, self.top);
    }
};

Deps.prototype._flush = function () {
    if (this.pending === 0) this.push(null);
    this._ended = true;
};

Deps.prototype.resolve = function (id, parent, cb) {
    var self = this;
    var opts = self.options;

    if (xhas(self.cache, parent.id, 'deps', id)
    && self.cache[parent.id].deps) {
        var file = self.cache[parent.id].deps[id];
        var pkg = self.pkgCache[file];
        if (pkg) return cb(null, file, pkg);
        return self.lookupPackage(file, function (err, pkg) {
            cb(null, file, pkg);
        });
    }

    var pkgdir;
    parent.packageFilter = function (p, x) {
        pkgdir = x;
        if (opts.packageFilter) return opts.packageFilter(p, x);
        else return p;
    };

    if (opts.extensions) parent.extensions = opts.extensions;
    if (opts.modules) parent.modules = opts.modules;

    self.resolver(id, parent, function onresolve (err, file, pkg) {
        if (err) return cb(err);
        if (!file) return cb(new Error(
            'module not found: "' + id + '" from file '
            + parent.filename
        ));

        if (pkg && pkgdir) pkg.__dirname = pkgdir;
        if (!pkg || !pkg.__dirname) {
            self.lookupPackage(file, function (err, p) {
                if (err) return cb(err);
                if (!p) p = {};
                if (!p.__dirname) p.__dirname = path.dirname(file);
                self.pkgCache[file] = p;
                onresolve(err, file, opts.packageFilter
                    ? opts.packageFilter(p, p.__dirname) : p
                );
            });
        }
        else cb(err, file, pkg);
    });
};

Deps.prototype.readFile = function (file, id, pkg) {
    var tr = through();
    if (this.cache && this.cache[file]) {
        tr.push(this.cache[file].source);
        tr.push(null);
        return tr;
    }
    var rs = fs.createReadStream(file);
    rs.on('error', function (err) { tr.emit('error', err) });
    this.emit('file', file, id);
    return rs.pipe(this.getTransforms(file, pkg));
};

Deps.prototype.getTransforms = function (file, pkg) {
    var self = this;
    var isTopLevel = this.entries.some(function (main) {
        var m = path.relative(path.dirname(main), file);
        return m.split(/[\\\/]/).indexOf('node_modules') < 0;
    });

    var transforms = [].concat(isTopLevel ? this.transforms : [])
        .concat(getTransforms(pkg, {
            globalTransform: this.globalTransforms,
            transformKey: this.options.transformKey
        }))
    ;
    if (transforms.length === 0) return through();

    var pending = transforms.length;
    var streams = [];
    var input = through();
    var output = through();
    var dup = duplexer(input, output);

    for (var i = 0; i < transforms.length; i++) (function (i) {
        makeTransform(transforms[i], function (err, trs) {
            if (err) return self.emit('error', err)
            streams[i] = trs;
            if (-- pending === 0) done();
        });
    })(i);
    return dup;

    function done () {
        var middle = combine.apply(null, streams);
        middle.on('error', function (err) {
            err.message += ' while parsing file: ' + file;
            if (!err.filename) err.filename = file;
            self.emit('error', err);
        });
        input.pipe(middle).pipe(output);
    }

    function makeTransform (tr, cb) {
        var trOpts = {};
        if (Array.isArray(tr)) {
            trOpts = tr[1];
            tr = tr[0];
        }
        if (typeof tr === 'function') {
            var t = tr(file, trOpts);
            self.emit('transform', t, file);
            nextTick(cb, null, wrapTransform(t));
        }
        else {
            loadTransform(tr, trOpts, function (err, trs) {
                if (err) return cb(err);
                cb(null, wrapTransform(trs));
            });
        }
    }

    function loadTransform (id, trOpts, cb) {
        var params = { basedir: path.dirname(file) };
        nodeResolve(id, params, function nr (err, res, again) {
            if (err && again) return cb(err);

            if (err) {
                params.basedir = pkg.__dirname;
                return nodeResolve(id, params, function (e, r) {
                    nr(e, r, true)
                });
            }

            if (!res) return cb(new Error(
                'cannot find transform module ' + tr
                + ' while transforming ' + file
            ));

            var r = require(res);
            if (typeof r !== 'function') {
                return cb(new Error('transform not a function'));
            }

            var trs = r(file, trOpts);
            self.emit('transform', trs, file);
            cb(null, trs);
        });
    }
};

Deps.prototype.walk = function (id, parent, cb) {
    var self = this;
    var opts = self.options;
    this.pending ++;

    var rec = {};
    if (typeof id === 'object') {
        rec = copy(id);
        if (rec.entry === false) delete rec.entry;
        id = rec.file || rec.id;
    }

    self.resolve(id, parent, function (err, file, pkg) {
        if (rec.expose) {
            self.options.modules[rec.expose] = file;
        }

        if (opts.postFilter && !opts.postFilter(id, file, pkg)) {
            if (--self.pending === 0) self.push(null);
            return cb(null, undefined);
        }
        if (err && rec.source) {
            file = rec.file;

            var ts = self.getTransforms(file, pkg);
            ts.pipe(concat(function (body) {
                rec.source = body.toString('utf8');
                fromSource(rec.source);
            }));
            return ts.end(rec.source);
        }
        if (err && self.options.ignoreMissing) {
            if (--self.pending === 0) self.push(null);
            self.emit('missing', id, parent);
            return cb(null, undefined);
        }
        if (err) return self.emit('error', err);
        if (self.visited[file]) {
            if (-- self.pending === 0) self.push(null);
            return cb && cb(null, file);
        }
        self.visited[file] = true;

        if (rec.source) {
            var ts = self.getTransforms(file, pkg);
            ts.pipe(concat(function (body) {
                rec.source = body.toString('utf8');
                fromSource(rec.source);
            }));
            return ts.end(rec.source);
        }

        var c = self.cache && self.cache[file];
        if (c) return fromDeps(file, c.source, c.package, Object.keys(c.deps));

        self.readFile(file, id, pkg).pipe(concat(function (body) {
            fromSource(body.toString('utf8'));
        }));

        function fromSource (src) {
            var deps = self.parseDeps(file, src);
            if (deps) fromDeps(file, src, pkg, deps);
        }
    });

    function fromDeps (file, src, pkg, deps) {
        var p = deps.length;
        var current = {
            id: file,
            filename: file,
            paths: self.paths,
            package: pkg
        };
        var resolved = {};

        deps.forEach(function (id) {
            if (opts.filter && !opts.filter(id)) {
                resolved[id] = false;
                if (--p === 0) done();
                return;
            }
            self.walk(id, current, function (err, r) {
                resolved[id] = r;
                if (--p === 0) done();
            });
        });
        if (deps.length === 0) done();

        function done () {
            if (!rec.id) rec.id = file;
            if (!rec.source) rec.source = src;
            if (!rec.deps) rec.deps = resolved;
            if (!rec.file) rec.file = file;

            if (self.entries.indexOf(file) >= 0) {
                rec.entry = true;
            }
            self.push(rec);

            if (cb) cb(null, file);
            if (-- self.pending === 0 && self._ended) self.push(null);
        }
    }
};

Deps.prototype.parseDeps = function (file, src, cb) {
    if (this.options.noParse === true) return [];
    if (/\.json$/.test(file)) return [];

    if (Array.isArray(this.options.noParse)
    && this.options.noParse.indexOf(file) >= 0) {
        return [];
    }

    try { var deps = detective(src) }
    catch (ex) {
        var message = ex && ex.message ? ex.message : ex;
        this.emit('error', new Error(
            'Parsing file ' + file + ': ' + message
        ));
        return;
    }
    return deps;
};

Deps.prototype.lookupPackage = function (file, cb) {
    var self = this;

    var cached = this.pkgCache[file];
    if (cached) return nextTick(cb, null, cached);
    if (cached === false) return nextTick(cb, null, undefined);

    var dirs = parents(path.dirname(file));

    (function next () {
        if (dirs.length === 0) {
            self.pkgCache[file] = false;
            return cb(null, undefined);
        }
        var dir = dirs.shift();
        if (dir.split(/[\\\/]/).slice(-1)[0] === 'node_modules') {
            return cb(null, undefined);
        }

        var pkgfile = path.join(dir, 'package.json');

        var cached = self.pkgCache[pkgfile];
        if (cached) return nextTick(cb, null, cached);
        else if (cached === false) return next();

        var pcached = self.pkgFileCachePending[pkgfile];
        if (pcached) return pcached.push(onpkg);
        pcached = self.pkgFileCachePending[pkgfile] = [];

        fs.readFile(pkgfile, function (err, src) {
            if (err) return onpkg();
            try { var pkg = JSON.parse(src) }
            catch (err) {
                return onpkg(new Error([
                    err + ' while parsing json file ' + pkgfile
                ].join('')))
            }
            pkg.__dirname = dir;

            self.pkgCache[pkgfile] = pkg;
            self.pkgCache[file] = pkg;
            onpkg(null, pkg);
        });

        function onpkg (err, pkg) {
            if (self.pkgFileCachePending[pkgfile]) {
                var fns = self.pkgFileCachePending[pkgfile];
                delete self.pkgFileCachePending[pkgfile];
                fns.forEach(function (f) { f(err, pkg) });
            }
            if (err) cb(err)
            else if (pkg) cb(null, pkg)
            else {
                self.pkgCache[pkgfile] = false;
                next();
            }
        }
    })();
};

function getTransforms (pkg, opts) {
    var trx = [];
    if (opts.transformKey) {
        var n = pkg;
        var keys = opts.transformKey;
        for (var i = 0; i < keys.length; i++) {
            if (n && typeof n === 'object') n = n[keys[i]];
            else break;
        }
        if (i === keys.length) {
            trx = [].concat(n).filter(Boolean);
        }
    }
    return trx.concat(opts.globalTransform || []);
}

function nextTick (cb) {
    var args = [].slice.call(arguments, 1);
    process.nextTick(function () { cb.apply(null, args) });
}

function xhas (obj) {
    if (!obj) return false;
    for (var i = 1; i < arguments.length; i++) {
        var key = arguments[i];
        if (!has(obj, key)) return false;
        obj = obj[key];
    }
    return true;
}

function has (obj, key) {
    return Object.prototype.hasOwnProperty.call(obj, key);
}

function wrapTransform (tr) {
    if (typeof tr.read === 'function') return tr;
    var input = through(), output = through();
    input.pipe(tr).pipe(output);
    var wrapper = duplexer(input, output);
    tr.on('error', function (err) { wrapper.emit('error', err) });
    return wrapper;
}
<|endoftext|>


<commit_before>"use strict";
var nodecss = require("node-css"),
  _ = require("lodash"),
  libpath = require("path");

var CSS = nodecss.CSS;
var rxReplacePath = /(\/|\\)/g;
var MEDIA_QUERY = "(min-device-pixel-ratio: 2) and (min-resolution: 192dpi)";
var css = new CSS();

function CSSImage() {
}

CSSImage.prototype.css = function(filepath, width, height, root, options) {
  var classname = "." + this.name(filepath, options);
  if (!options) { options = {}; }
  if (options.retina) {
    options.media = MEDIA_QUERY;
  }
  var squeeze = !!options.squeeze ? +options.squeeze : 1;
  var _width = Math.floor(width / squeeze);
  var _height = Math.floor(height / squeeze);
  return css.statement(classname, {
    width: _width + "px",
    height: _height + "px",
    "background-image": this.url(filepath, root, options.retina),
    "background-size": "" + _width  + "px " + _height + "px"
  }, options);
};

CSSImage.prototype.scssVars = function(filepath, _width, _height, options) {
  var name = this.name(filepath, options);
  var squeeze = (options && !!options.squeeze) ? +options.squeeze : 1;
  var width = Math.floor(_width / squeeze);
  var height = Math.floor(_height / squeeze);
  var root = (options && options.root) || "";
  var retina = options && !!options.retina;
  var fullpath = this.normalizePath(filepath, root, retina);

  return "$" + name + ": (\n" +
         "\twidth: " + width + "px,\n" +
         "\theight: " + height + "px\n" +
         "\tfullpath: \"" + fullpath + "\"\n" +
         "\tpath: \"" + filepath + "\"\n" +
         ");\n" +
         "$" + name + "__width: " + width + "px;\n" +
         "$" + name + "__height: " + height + "px;\n" +
         "$" + name + "__path: '" + fullpath + "';\n\n";
};

CSSImage.prototype.scssMixin = function(filepath, _width, _height, root, options) {
  var name = this.name(filepath, options);
  if (!options) { options = {}; }
  var classname = "@mixin " + name + "()";
  var isRetina = !!options.retina;
  var indent = css.options(options, "indent");
  var squeeze = (options && !!options.squeeze) ? +options.squeeze : 1;
  var width = Math.floor(_width / squeeze);
  var height = Math.floor(_height / squeeze);

  var scssMixin = css.body({
    width: width + "px",
    height: height + "px",
    "background-image": this.url(filepath, root),
    "background-size": "" + width  + "px " + height + "px"
  }, {indent: indent});

  if (isRetina) {
    var body = css.body({
      width: width + "px",
      height: height + "px",
      "background-image": this.url(filepath, root, options.retina),
      "background-size": "" + width  + "px " + height + "px"
    }, {indent: indent + indent});
    scssMixin += indent + "@media " + MEDIA_QUERY + " {\n" + body + indent + "}\n";
  }
  return classname + " {\n" + scssMixin + "}\n";
};

CSSImage.prototype.scss = function(filepath, width, height, root, options) {
  return this.scssMixin(filepath, width, height, root, options) +
         this.scssVars(filepath, width, height, options);
};

CSSImage.prototype.url = function(filepath, root, retina) {
  return "url(" + this.normalizePath(filepath, root, retina) + ")";
};

CSSImage.prototype.normalizePath = function(filepath, root, retina) {
  var name = libpath.basename(filepath);
  var ext = libpath.extname(filepath);
  if (!!retina) {
    var postfix = (typeof retina === "string") ? retina : "-50pc";
    name = name.replace(ext, postfix + ext);
  }
  var normalizedPath = libpath.join(this.normalizeFolder(filepath, root), name);
  normalizedPath = normalizedPath.replace(rxReplacePath, "/");
  return normalizedPath;
};

CSSImage.prototype.normalizeFolder = function(filepath, root) {
  var folder = libpath.dirname(filepath);
  if (folder[0] === "." && folder[1] !== ".") { folder = folder.slice(1); }
  if (folder[0] === "/") { folder = folder.slice(1); }
  var result = root ? libpath.join(root, folder) : folder;
  return result.replace(rxReplacePath, "/");
};

CSSImage.prototype.name = function(filepath, options) {
  var postfix = options && options.postfix ? options.postfix : "";
  if (options && options.squeeze) { postfix += "-s" + options.squeeze; }
  var prefix = options && (typeof options.prefix !== "undefined") ? options.prefix : "img_";
  var separator = (options && options.separator) || "_";
  var filename = libpath.basename(filepath);
  var ext = libpath.extname(filepath);
  var name = filename.slice(0, filename.length - ext.length).replace(/\./, "");
  var folder = this.normalizeFolder(filepath);
  if (folder === "") { return prefix + name + postfix; }

  // windows fix
  folder = folder.replace(rxReplacePath, separator);
  return prefix + folder + separator + name + postfix;
};

var _cssImage = new CSSImage();
function cssimage(images, _options) {
  var options = _.omit(_options, ["retina", "squeeze"]);
  var isCss = !!options.css;
  var isScss = !!options.scss;
  var root = options.root || "";
  var result = "";
  var isRetina = _options && !!_options.retina;
  var squeeze = (_options && _options.squeeze) || 1;
  for (var i = 0; i < images.length; i++) {
    var img = images[i];
    if (isCss) {
      result += _cssImage.css(img.file, img.width, img.height, root, options);
      if (isRetina) {
        result += _cssImage.css(img.file, img.width, img.height, root, _.extend({
          retina: true
        }, options));
      }
      if (squeeze !== 1) {
        result += _cssImage.css(img.file, img.width, img.height, root, _.extend({
          squeeze: squeeze
        }, options));
      }
    }
    if (isScss) {
      result += _cssImage.scss(img.file, img.width, img.height, root, _.extend({
        retina: isRetina
      }, options));
      if (squeeze !== 1) {
        result += _cssImage.scss(img.file, img.width, img.height, root, _.extend({
          squeeze: squeeze
        }, options));
      }
    }
  }
  return result;
}

module.exports = cssimage;
module.exports.CSSImage = CSSImage;
<commit_msg>Added missing comas<commit_after>"use strict";
var nodecss = require("node-css"),
  _ = require("lodash"),
  libpath = require("path");

var CSS = nodecss.CSS;
var rxReplacePath = /(\/|\\)/g;
var MEDIA_QUERY = "(min-device-pixel-ratio: 2) and (min-resolution: 192dpi)";
var css = new CSS();

function CSSImage() {
}

CSSImage.prototype.css = function(filepath, width, height, root, options) {
  var classname = "." + this.name(filepath, options);
  if (!options) { options = {}; }
  if (options.retina) {
    options.media = MEDIA_QUERY;
  }
  var squeeze = !!options.squeeze ? +options.squeeze : 1;
  var _width = Math.floor(width / squeeze);
  var _height = Math.floor(height / squeeze);
  return css.statement(classname, {
    width: _width + "px",
    height: _height + "px",
    "background-image": this.url(filepath, root, options.retina),
    "background-size": "" + _width  + "px " + _height + "px"
  }, options);
};

CSSImage.prototype.scssVars = function(filepath, _width, _height, options) {
  var name = this.name(filepath, options);
  var squeeze = (options && !!options.squeeze) ? +options.squeeze : 1;
  var width = Math.floor(_width / squeeze);
  var height = Math.floor(_height / squeeze);
  var root = (options && options.root) || "";
  var retina = options && !!options.retina;
  var fullpath = this.normalizePath(filepath, root, retina);

  return "$" + name + ": (\n" +
         "\twidth: " + width + "px,\n" +
         "\theight: " + height + "px,\n" +
         "\tfullpath: \"" + fullpath + "\",\n" +
         "\tpath: \"" + filepath + "\"\n" +
         ");\n" +
         "$" + name + "__width: " + width + "px;\n" +
         "$" + name + "__height: " + height + "px;\n" +
         "$" + name + "__path: '" + fullpath + "';\n\n";
};

CSSImage.prototype.scssMixin = function(filepath, _width, _height, root, options) {
  var name = this.name(filepath, options);
  if (!options) { options = {}; }
  var classname = "@mixin " + name + "()";
  var isRetina = !!options.retina;
  var indent = css.options(options, "indent");
  var squeeze = (options && !!options.squeeze) ? +options.squeeze : 1;
  var width = Math.floor(_width / squeeze);
  var height = Math.floor(_height / squeeze);

  var scssMixin = css.body({
    width: width + "px",
    height: height + "px",
    "background-image": this.url(filepath, root),
    "background-size": "" + width  + "px " + height + "px"
  }, {indent: indent});

  if (isRetina) {
    var body = css.body({
      width: width + "px",
      height: height + "px",
      "background-image": this.url(filepath, root, options.retina),
      "background-size": "" + width  + "px " + height + "px"
    }, {indent: indent + indent});
    scssMixin += indent + "@media " + MEDIA_QUERY + " {\n" + body + indent + "}\n";
  }
  return classname + " {\n" + scssMixin + "}\n";
};

CSSImage.prototype.scss = function(filepath, width, height, root, options) {
  return this.scssMixin(filepath, width, height, root, options) +
         this.scssVars(filepath, width, height, options);
};

CSSImage.prototype.url = function(filepath, root, retina) {
  return "url(" + this.normalizePath(filepath, root, retina) + ")";
};

CSSImage.prototype.normalizePath = function(filepath, root, retina) {
  var name = libpath.basename(filepath);
  var ext = libpath.extname(filepath);
  if (!!retina) {
    var postfix = (typeof retina === "string") ? retina : "-50pc";
    name = name.replace(ext, postfix + ext);
  }
  var normalizedPath = libpath.join(this.normalizeFolder(filepath, root), name);
  normalizedPath = normalizedPath.replace(rxReplacePath, "/");
  return normalizedPath;
};

CSSImage.prototype.normalizeFolder = function(filepath, root) {
  var folder = libpath.dirname(filepath);
  if (folder[0] === "." && folder[1] !== ".") { folder = folder.slice(1); }
  if (folder[0] === "/") { folder = folder.slice(1); }
  var result = root ? libpath.join(root, folder) : folder;
  return result.replace(rxReplacePath, "/");
};

CSSImage.prototype.name = function(filepath, options) {
  var postfix = options && options.postfix ? options.postfix : "";
  if (options && options.squeeze) { postfix += "-s" + options.squeeze; }
  var prefix = options && (typeof options.prefix !== "undefined") ? options.prefix : "img_";
  var separator = (options && options.separator) || "_";
  var filename = libpath.basename(filepath);
  var ext = libpath.extname(filepath);
  var name = filename.slice(0, filename.length - ext.length).replace(/\./, "");
  var folder = this.normalizeFolder(filepath);
  if (folder === "") { return prefix + name + postfix; }

  // windows fix
  folder = folder.replace(rxReplacePath, separator);
  return prefix + folder + separator + name + postfix;
};

var _cssImage = new CSSImage();
function cssimage(images, _options) {
  var options = _.omit(_options, ["retina", "squeeze"]);
  var isCss = !!options.css;
  var isScss = !!options.scss;
  var root = options.root || "";
  var result = "";
  var isRetina = _options && !!_options.retina;
  var squeeze = (_options && _options.squeeze) || 1;
  for (var i = 0; i < images.length; i++) {
    var img = images[i];
    if (isCss) {
      result += _cssImage.css(img.file, img.width, img.height, root, options);
      if (isRetina) {
        result += _cssImage.css(img.file, img.width, img.height, root, _.extend({
          retina: true
        }, options));
      }
      if (squeeze !== 1) {
        result += _cssImage.css(img.file, img.width, img.height, root, _.extend({
          squeeze: squeeze
        }, options));
      }
    }
    if (isScss) {
      result += _cssImage.scss(img.file, img.width, img.height, root, _.extend({
        retina: isRetina
      }, options));
      if (squeeze !== 1) {
        result += _cssImage.scss(img.file, img.width, img.height, root, _.extend({
          squeeze: squeeze
        }, options));
      }
    }
  }
  return result;
}

module.exports = cssimage;
module.exports.CSSImage = CSSImage;
<|endoftext|>


<commit_before>var through = require('through');
var copy = require('shallow-copy');
var browserify = require('browserify');
var fs = require('fs');
var chokidar = require('chokidar');

module.exports = watchify;
watchify.browserify = browserify;

function watchify (opts) {
    if (!opts) opts = {};
    var b = typeof opts.bundle === 'function' ? opts : browserify(opts);
    var cache = {};
    var pkgcache = {};
    var watching = {};
    var pending = false;
    var queuedCloses = {};
    var queuedDeps = {};
    var changingDeps = {};
    var first = true;

    if (opts.cache) {
        cache = opts.cache;
        delete opts.cache;
        first = false;
    }

    if (opts.pkgcache) {
        pkgcache = opts.pkgcache;
        delete opts.pkgcache;
    }

    b.on('package', function (file, pkg) {
        pkgcache[file] = pkg;
    });

    b.on('dep', function (dep) {
        queuedDeps[dep.id] = copy(dep);
    });

    var fwatchers = {};
    var fwatcherFiles = {};
    b.on('bundle', function (bundle) {
        bundle.on('transform', function (tr, mfile) {
            if (!fwatchers[mfile]) fwatchers[mfile] = [];
            if (!fwatcherFiles[mfile]) fwatcherFiles[mfile] = [];

            tr.on('file', function (file) {
                if (!fwatchers[mfile]) return;
                if (fwatchers[mfile].indexOf(file) >= 0) return;

                var w = chokidar.watch(file, {persistent: true});
                w.on('error', b.emit.bind(b, 'error'));
                w.on('change', function () {
                    invalidate(mfile);
                });
                fwatchers[mfile].push(w);
                fwatcherFiles[mfile].push(file);
            });
        });
    });

    var watchers = {};
    function addDep (dep) {
        if (watching[dep.id]) return;
        watching[dep.id] = true;
        cache[dep.id] = dep;

        var watcher = chokidar.watch(dep.id, {persistent: true});
        watchers[dep.id] = watcher;
        watcher.on('error', b.emit.bind(b, 'error'));
        watcher.on('change', function () {
            invalidate(dep.id);
        });
    }

    function invalidate (id) {
        delete cache[id];
        if (fwatchers[id]) {
            fwatchers[id].forEach(function (w) {
                queuedCloses[id + '-' + id] = w;
            });
            delete fwatchers[id];
            delete fwatcherFiles[id];
        }
        queuedCloses[id] = watchers[id];
        changingDeps[id] = true

        // wait for the disk/editor to quiet down first:
        if (!pending) setTimeout(function () {
            pending = false;
            b.emit('update', Object.keys(changingDeps));
            changingDeps = {};

        }, opts.delay || 600);
        pending = true;
    }

    var bundle = b.bundle.bind(b);
    b.bundle = function (opts_, cb) {
        if (b._pending) return bundle(opts_, cb);

        if (typeof opts_ === 'function') {
            cb = opts_;
            opts_ = {};
        }
        if (!opts_) opts_ = {};
        if (!first) opts_.cache = cache;
        opts_.includePackage = true;
        opts_.packageCache = pkgcache;

        // we only want to mess with the listeners if the bundle was created
        // successfully, e.g. on the 'end' event.
        var outStream = bundle(opts_, cb);
        outStream.on('error', function (err) {
            var updated = false;
            b.once('update', function () { updated = true });

            if (err.type === 'not found') {
                (function f () {
                    if (updated) return;
                    fs.exists(err.filename, function (ex) {
                        if (ex) b.emit('update', [ err.filename ])
                        else setTimeout(f, opts.delay || 600)
                    });
                })();
            }
        });
        outStream.on('end', end);
        function end () {
            first = false;
            var depId;
            for (depId in queuedCloses) {
                queuedCloses[depId].close();
                watching[depId] = false;
            }
            queuedCloses = {};
            for (depId in queuedDeps) {
                addDep(queuedDeps[depId]);
            }
            queuedDeps = {};
        }
        return outStream;
    };

    return b;
}
<commit_msg>add back .close<commit_after>var through = require('through');
var copy = require('shallow-copy');
var browserify = require('browserify');
var fs = require('fs');
var chokidar = require('chokidar');

module.exports = watchify;
watchify.browserify = browserify;

function watchify (opts) {
    if (!opts) opts = {};
    var b = typeof opts.bundle === 'function' ? opts : browserify(opts);
    var cache = {};
    var pkgcache = {};
    var watching = {};
    var pending = false;
    var queuedCloses = {};
    var queuedDeps = {};
    var changingDeps = {};
    var first = true;

    if (opts.cache) {
        cache = opts.cache;
        delete opts.cache;
        first = false;
    }

    if (opts.pkgcache) {
        pkgcache = opts.pkgcache;
        delete opts.pkgcache;
    }

    b.on('package', function (file, pkg) {
        pkgcache[file] = pkg;
    });

    b.on('dep', function (dep) {
        queuedDeps[dep.id] = copy(dep);
    });

    var fwatchers = {};
    var fwatcherFiles = {};
    b.on('bundle', function (bundle) {
        bundle.on('transform', function (tr, mfile) {
            if (!fwatchers[mfile]) fwatchers[mfile] = [];
            if (!fwatcherFiles[mfile]) fwatcherFiles[mfile] = [];

            tr.on('file', function (file) {
                if (!fwatchers[mfile]) return;
                if (fwatchers[mfile].indexOf(file) >= 0) return;

                var w = chokidar.watch(file, {persistent: true});
                w.on('error', b.emit.bind(b, 'error'));
                w.on('change', function () {
                    invalidate(mfile);
                });
                fwatchers[mfile].push(w);
                fwatcherFiles[mfile].push(file);
            });
        });
    });

    var watchers = {};
    function addDep (dep) {
        if (watching[dep.id]) return;
        watching[dep.id] = true;
        cache[dep.id] = dep;

        var watcher = chokidar.watch(dep.id, {persistent: true});
        watchers[dep.id] = watcher;
        watcher.on('error', b.emit.bind(b, 'error'));
        watcher.on('change', function () {
            invalidate(dep.id);
        });
    }

    function invalidate (id) {
        delete cache[id];
        if (fwatchers[id]) {
            fwatchers[id].forEach(function (w) {
                queuedCloses[id + '-' + id] = w;
            });
            delete fwatchers[id];
            delete fwatcherFiles[id];
        }
        queuedCloses[id] = watchers[id];
        changingDeps[id] = true

        // wait for the disk/editor to quiet down first:
        if (!pending) setTimeout(function () {
            pending = false;
            b.emit('update', Object.keys(changingDeps));
            changingDeps = {};

        }, opts.delay || 600);
        pending = true;
    }

    var bundle = b.bundle.bind(b);
    b.close = function () {
        Object.keys(fwatchers).forEach(function (id) {
            fwatchers[id].forEach(function (w) { w.close() });
        });
        Object.keys(watchers).forEach(function (id) {
            watchers[id].close();
        });
    };

    b.bundle = function (opts_, cb) {
        if (b._pending) return bundle(opts_, cb);

        if (typeof opts_ === 'function') {
            cb = opts_;
            opts_ = {};
        }
        if (!opts_) opts_ = {};
        if (!first) opts_.cache = cache;
        opts_.includePackage = true;
        opts_.packageCache = pkgcache;

        // we only want to mess with the listeners if the bundle was created
        // successfully, e.g. on the 'end' event.
        var outStream = bundle(opts_, cb);
        outStream.on('error', function (err) {
            var updated = false;
            b.once('update', function () { updated = true });

            if (err.type === 'not found') {
                (function f () {
                    if (updated) return;
                    fs.exists(err.filename, function (ex) {
                        if (ex) b.emit('update', [ err.filename ])
                        else setTimeout(f, opts.delay || 600)
                    });
                })();
            }
        });
        outStream.on('end', end);
        function end () {
            first = false;
            var depId;
            for (depId in queuedCloses) {
                queuedCloses[depId].close();
                watching[depId] = false;
            }
            queuedCloses = {};
            for (depId in queuedDeps) {
                addDep(queuedDeps[depId]);
            }
            queuedDeps = {};
        }
        return outStream;
    };

    return b;
}
<|endoftext|>


<commit_before>var _ = require('lodash');

var temporalDefaultOptions = {
  // runs the insert within the sequelize hook chain, disable
  // for increased performance
  blocking: true,
  full: false
};

var excludeAttributes = function(obj, attrsToExclude){
  // fancy way to exclude attributes
  return _.omit(obj, _.partial(_.rearg(_.contains,0,2,1), attrsToExclude));
}

var Temporal = function(model, sequelize, temporalOptions){
  temporalOptions = _.extend({},temporalDefaultOptions, temporalOptions);

  var Sequelize = sequelize.Sequelize;

  var historyName = model.name + 'History';
  //var historyName = model.getTableName() + 'History';
  //var historyName = model.options.name.singular + 'History';

  var historyOwnAttrs = {
    hid: {
      type:          Sequelize.BIGINT,
      primaryKey:    true,
      autoIncrement: true,
      unique: true
    },
    archivedAt: {
      type: Sequelize.DATE,
      allowNull: false,
      defaultValue: Sequelize.NOW
    }
  };

  var excludedAttributes = ["Model","unique","primaryKey","autoIncrement", "set", "get", "_modelAttribute"];
  var historyAttributes = _(model.rawAttributes).mapValues(function(v){
    v = excludeAttributes(v, excludedAttributes);
    // remove the "NOW" defaultValue for the default timestamps
    // we want to save them, but just a copy from our master record
    if(v.fieldName == "createdAt" || v.fieldName == "updatedAt"){
      v.type = Sequelize.DATE;
    }
    return v;
  }).assign(historyOwnAttrs).value();
  // If the order matters, use this:
  //historyAttributes = _.assign({}, historyOwnAttrs, historyAttributes);

  var historyOwnOptions = {
    timestamps: false
  };
  var excludedNames = ["name", "tableName", "sequelize", "uniqueKeys", "hasPrimaryKey", "hooks", "scopes", "instanceMethods", "defaultScope"];
  var modelOptions = excludeAttributes(model.options, excludedNames);
  var historyOptions = _.assign({}, modelOptions, historyOwnOptions);

  // We want to delete indexes that have unique constraint
  var indexes = historyOptions.indexes;
  if(Array.isArray(indexes)){
     historyOptions.indexes = indexes.filter(function(index){return !index.unique && index.type != 'UNIQUE';});
  }

  var modelHistory = sequelize.define(historyName, historyAttributes, historyOptions);

  // we already get the updatedAt timestamp from our models
  var insertHook = function(obj, options){
    var dataValues = (!temporalOptions.full && obj._previousDataValues) || obj.dataValues;
    var historyRecord = modelHistory.create(dataValues, {transaction: options.transaction});
    if(temporalOptions.blocking){
      return historyRecord;
    }
  }
  var insertBulkHook = function(options){
    if(!options.individualHooks){
      var queryAll = model.findAll({where: options.where, transaction: options.transaction}).then(function(hits){
        if(hits){
          hits = _.pluck(hits, 'dataValues');
          return modelHistory.bulkCreate(hits, {transaction: options.transaction});
        }
      });
      if(temporalOptions.blocking){
        return queryAll;
      }
    }
  }

  // use `after` to be nonBlocking
  // all hooks just create a copy
  if (temporalOptions.full) {
    model.addHook('afterCreate', insertHook);
    model.addHook('afterUpdate', insertHook);
    model.addHook('afterDestroy', insertHook);
    model.addHook('afterRestore', insertHook);
  } else {
    model.addHook('beforeUpdate', insertHook);
    model.addHook('beforeDestroy', insertHook);
  }

  model.addHook('beforeBulkUpdate', insertBulkHook);
  model.addHook('beforeBulkDestroy', insertBulkHook);

  var readOnlyHook = function(){
    throw new Error("This is a read-only history database. You aren't allowed to modify it.");
  };

  modelHistory.addHook('beforeUpdate', readOnlyHook);
  modelHistory.addHook('beforeDestroy', readOnlyHook);

  return model;
};

module.exports = Temporal;
<commit_msg>Updates for lodash 4<commit_after>var _ = require('lodash');

var temporalDefaultOptions = {
  // runs the insert within the sequelize hook chain, disable
  // for increased performance
  blocking: true,
  full: false
};

var excludeAttributes = function(obj, attrsToExclude){
  // fancy way to exclude attributes
  return _.omit(obj, attrsToExclude);
}

var Temporal = function(model, sequelize, temporalOptions){
  temporalOptions = _.extend({},temporalDefaultOptions, temporalOptions);

  var Sequelize = sequelize.Sequelize;

  var historyName = model.name + 'History';
  //var historyName = model.getTableName() + 'History';
  //var historyName = model.options.name.singular + 'History';

  var historyOwnAttrs = {
    hid: {
      type:          Sequelize.BIGINT,
      primaryKey:    true,
      autoIncrement: true,
      unique: true
    },
    archivedAt: {
      type: Sequelize.DATE,
      allowNull: false,
      defaultValue: Sequelize.NOW
    }
  };

  var excludedAttributes = ["Model","unique","primaryKey","autoIncrement", "set", "get", "_modelAttribute"];
  var historyAttributes = _(model.rawAttributes).mapValues(function(v){
    v = excludeAttributes(v, excludedAttributes);
    // remove the "NOW" defaultValue for the default timestamps
    // we want to save them, but just a copy from our master record
    if(v.fieldName == "createdAt" || v.fieldName == "updatedAt"){
      v.type = Sequelize.DATE;
    }
    return v;
  }).assign(historyOwnAttrs).value();
  // If the order matters, use this:
  //historyAttributes = _.assign({}, historyOwnAttrs, historyAttributes);

  var historyOwnOptions = {
    timestamps: false
  };
  var excludedNames = ["name", "tableName", "sequelize", "uniqueKeys", "hasPrimaryKey", "hooks", "scopes", "instanceMethods", "defaultScope"];
  var modelOptions = excludeAttributes(model.options, excludedNames);
  var historyOptions = _.assign({}, modelOptions, historyOwnOptions);

  // We want to delete indexes that have unique constraint
  var indexes = historyOptions.indexes;
  if(Array.isArray(indexes)){
     historyOptions.indexes = indexes.filter(function(index){return !index.unique && index.type != 'UNIQUE';});
  }

  var modelHistory = sequelize.define(historyName, historyAttributes, historyOptions);

  // we already get the updatedAt timestamp from our models
  var insertHook = function(obj, options){
    var dataValues = (!temporalOptions.full && obj._previousDataValues) || obj.dataValues;
    var historyRecord = modelHistory.create(dataValues, {transaction: options.transaction});
    if(temporalOptions.blocking){
      return historyRecord;
    }
  }
  var insertBulkHook = function(options){
    if(!options.individualHooks){
      var queryAll = model.findAll({where: options.where, transaction: options.transaction}).then(function(hits){
        if(hits){
          hits = _.map(hits, 'dataValues');
          return modelHistory.bulkCreate(hits, {transaction: options.transaction});
        }
      });
      if(temporalOptions.blocking){
        return queryAll;
      }
    }
  }

  // use `after` to be nonBlocking
  // all hooks just create a copy
  if (temporalOptions.full) {
    model.addHook('afterCreate', insertHook);
    model.addHook('afterUpdate', insertHook);
    model.addHook('afterDestroy', insertHook);
    model.addHook('afterRestore', insertHook);
  } else {
    model.addHook('beforeUpdate', insertHook);
    model.addHook('beforeDestroy', insertHook);
  }

  model.addHook('beforeBulkUpdate', insertBulkHook);
  model.addHook('beforeBulkDestroy', insertBulkHook);

  var readOnlyHook = function(){
    throw new Error("This is a read-only history database. You aren't allowed to modify it.");
  };

  modelHistory.addHook('beforeUpdate', readOnlyHook);
  modelHistory.addHook('beforeDestroy', readOnlyHook);

  return model;
};

module.exports = Temporal;
<|endoftext|>


<commit_before>var RedisStore = require('connect-redis');
var url = require('url');
var envVariables = ['REDIS_SESSION_URI', 'REDIS_URI', 'REDIS_SESSION_URL', 'REDIS_URL', 'REDISTOGO_URL', 'OPENREDIS_URL'];
var fallback = 'redis://localhost:6379'

module.exports = function(connect){
  var store = RedisStore(connect);

  function KrakenRedisStore (options) {
    if(!options) {
      options = {};
    } else if(typeof options === 'string') {
      options = { url: options };
    }
    if(!options.host) {
      var redisUrl = options.url;
      if(!redisUrl) {
        for(var i = 0; i < envVariables.length; i++) {
          if(redisUrl = process.env[envVariables[i]]) {
            break;
          }
        }
      }
      var config = url.parse(redisUrl || fallback);
      options.host = config.hostname;
      if(config.port) {
        options.port = config.port;
      }
      if(config.path && config.path !== '/') {
        options.db = config.path.replace(/^\//, '');
      }
      if(config.auth) {
        options.pass = config.auth.split(":")[1];
      }
    }
    store.call(this, options);
  }
  KrakenRedisStore.prototype = store.prototype;
  return KrakenRedisStore;
};
<commit_msg>Use util.inherits instead of simple prototype assignment.<commit_after>var RedisStore = require('connect-redis');
var url = require('url');
var util = require('util');
var envVariables = ['REDIS_SESSION_URI', 'REDIS_URI', 'REDIS_SESSION_URL', 'REDIS_URL', 'REDISTOGO_URL', 'OPENREDIS_URL'];
var fallback = 'redis://localhost:6379'

module.exports = function(connect){
  var store = RedisStore(connect);

  function AutoconfigRedisStore (options) {
    if(!options) {
      options = {};
    } else if(typeof options === 'string') {
      options = { url: options };
    }
    if(!options.host) {
      var redisUrl = options.url;
      if(!redisUrl) {
        for(var i = 0; i < envVariables.length; i++) {
          if(redisUrl = process.env[envVariables[i]]) {
            break;
          }
        }
      }
      var config = url.parse(redisUrl || fallback);
      options.host = config.hostname;
      if(config.port) {
        options.port = config.port;
      }
      if(config.path && config.path !== '/') {
        options.db = config.path.replace(/^\//, '');
      }
      if(config.auth) {
        options.pass = config.auth.split(":")[1];
      }
    }
    store.call(this, options);
  }
  util.inherits(AutoconfigRedisStore, store);
  return AutoconfigRedisStore;
};
<|endoftext|>


<commit_before>// TODO(sww): zero allocations! (out param?)
function single (box, motion, box2) {
  var newX = moveAxis(box, motion, box2, 0)
  var newY = moveAxis(box, motion, box2, 1)

  return [newX, newY]
}

// TODO(sww): zero allocations! (out param?)
// TODO(sww): only call cb() on each axis' winner (not ALL candidates)
function set (box, motion, getBox, cb) {
  var box2 = undefined
  var offset = [motion[0], motion[1]]

  function heresABox (box2) {
    if (box2 !== null) {
      var leading = motion[0] > 0 ? box[0] + box[2] : box[0]
      var newX = moveAxis(box, motion, box2, 0)
      if (newX !== leading + motion[0]) {
        cb(box2, 0, motion[0] > 0 ? 1 : -1)
      }
      if (motion[0] > 0) { offset[0] = Math.min(offset[0], newX) }
      else { offset[0] = Math.max(offset[0], newX) }

      var leading = motion[1] > 0 ? box[1] + box[3] : box[1]
      var newY = moveAxis(box, motion, box2, 1)
      if (newY !== leading + motion[1]) {
        cb(box2, 1, motion[1] > 0 ? 1 : -1)
      }
      if (motion[1] > 0) { offset[1] = Math.min(offset[1], newY) }
      else { offset[1] = Math.max(offset[1], newY) }
    }
  }

  getBox(heresABox)

  return offset
}

function moveAxis (box, motion, box2, axis) {
  var leading = motion[axis] > 0 ? box[axis] + box[axis + 2] : box[axis]
  var otherAxis = (axis === 0 ? 1 : 0)

  // Bail if there's no other-axis intersection
  if (box[otherAxis] > box2[otherAxis] + box2[otherAxis + 2]) {
    return motion[axis]
  }
  if (box[otherAxis] + box[otherAxis + 2] < box2[otherAxis]) {
    return motion[axis]
  }

  // Axis hit (right/bottom)
  if (leading <= box2[axis] && leading + motion[axis] > box2[axis]) {
    return box2[axis] - leading
  }

  // Axis hit (left/top)
  if (leading >= box2[axis] + box2[axis + 2] && leading + motion[axis] < box2[axis] + box2[axis + 2]) {
    return (box2[axis] + box2[axis + 2]) - leading
  }

  return motion[axis]
}

module.exports.single = single
module.exports.set = set
<commit_msg>one callback per axis winner<commit_after>// TODO(sww): zero allocations! (out param?)
function single (box, motion, box2) {
  var newX = moveAxis(box, motion, box2, 0)
  var newY = moveAxis(box, motion, box2, 1)

  return [newX, newY]
}

// TODO(sww): zero allocations! (out param?)
function set (box, motion, getBox, cb) {
  var box2 = undefined
  var offset = [motion[0], motion[1]]
  var winnerX = undefined
  var winnerY = undefined

  function heresABox (box2) {
    if (box2 !== null) {
      var leading = motion[0] > 0 ? box[0] + box[2] : box[0]
      var newX = moveAxis(box, motion, box2, 0)
      // decide winner
      if (motion[0] > 0 && newX < offset[0]) {
        offset[0] = newX
        winnerX = box2
      }
      else if (motion[0] < 0 && newX > offset[0]) {
        offset[0] = newX
        winnerX = box2
      }

      var leading = motion[1] > 0 ? box[1] + box[3] : box[1]
      var newY = moveAxis(box, motion, box2, 1)
      // decide winner
      if (motion[1] > 0 && newY < offset[1]) {
        offset[1] = newY
        winnerY = box2
      }
      else if (motion[1] < 0 && newY > offset[1]) {
        offset[1] = newY
        winnerY = box2
      }
    }
  }

  getBox(heresABox)

  // winner callbacks for each axis
  if (winnerX) {
    cb(winnerX, 0, motion[0] > 0 ? 1 : -1)
  }
  if (winnerY) {
    cb(winnerY, 1, motion[1] > 0 ? 1 : -1)
  }

  return offset
}

function moveAxis (box, motion, box2, axis) {
  var leading = motion[axis] > 0 ? box[axis] + box[axis + 2] : box[axis]
  var otherAxis = (axis === 0 ? 1 : 0)

  // Bail if there's no other-axis intersection
  if (box[otherAxis] > box2[otherAxis] + box2[otherAxis + 2]) {
    return motion[axis]
  }
  if (box[otherAxis] + box[otherAxis + 2] < box2[otherAxis]) {
    return motion[axis]
  }

  // Axis hit (right/bottom)
  if (leading <= box2[axis] && leading + motion[axis] > box2[axis]) {
    return box2[axis] - leading
  }

  // Axis hit (left/top)
  if (leading >= box2[axis] + box2[axis + 2] && leading + motion[axis] < box2[axis] + box2[axis + 2]) {
    return (box2[axis] + box2[axis + 2]) - leading
  }

  return motion[axis]
}

module.exports.single = single
module.exports.set = set
<|endoftext|>


<commit_before>var inventoryMap = new Map();
inventoryMap.set("transfer-in-doc-ext", require('./src/managers/inventory/transfer-in-doc-ext-manager'));
inventoryMap.set("transfer-in-doc", require('./src/managers/inventory/transfer-in-doc-manager'));
inventoryMap.set("transfer-out-doc", require('./src/managers/inventory/transfer-out-doc-manager'));
inventoryMap.set("inventory", require('./src/managers/inventory/inventory-manager'));
inventoryMap.set("inventory-movement", require('./src/managers/inventory/inventory-movement-manager'));

inventoryMap.set("efr-kb-rtt", require('./src/managers/inventory/efr-kb-rtt-manager'));
// inventoryMap.set("adjustment", require('./src/managers/inventory/adjustment-manager'));
inventoryMap.set("efr-kb-fng", require('./src/managers/inventory/efr-kb-fng-manager'));
inventoryMap.set("efr-kb-rtf", require('./src/managers/inventory/efr-kb-rtf-manager'));
inventoryMap.set("efr-kb-rtp", require('./src/managers/inventory/efr-kb-rtp-manager'));
inventoryMap.set("efr-kb-rtu", require('./src/managers/inventory/efr-kb-rtu-manager'));
inventoryMap.set("efr-kb-rtd", require('./src/managers/inventory/efr-kb-rtd-manager'));
inventoryMap.set("efr-kb-exb", require('./src/managers/inventory/efr-kb-exb-manager'));
inventoryMap.set("efr-kb-exp", require('./src/managers/inventory/efr-kb-exp-manager'));
inventoryMap.set("efr-kb-alt", require('./src/managers/inventory/efr-kb-alt-manager'));
inventoryMap.set("efr-tb-act", require('./src/managers/inventory/efr-tb-act-manager'));
inventoryMap.set("efr-tb-bat", require('./src/managers/inventory/efr-tb-bat-manager'));
inventoryMap.set("efr-tb-bbp", require('./src/managers/inventory/efr-tb-bbp-manager'));
inventoryMap.set("efr-tb-bbt", require('./src/managers/inventory/efr-tb-bbt-manager'));
inventoryMap.set("efr-tb-bjb", require('./src/managers/inventory/efr-tb-bjb-manager'));
inventoryMap.set("efr-tb-bjr", require('./src/managers/inventory/efr-tb-bjr-manager'));
inventoryMap.set("efr-tb-brd", require('./src/managers/inventory/efr-tb-brd-manager'));
inventoryMap.set("efr-tb-brt", require('./src/managers/inventory/efr-tb-brt-manager'));
inventoryMap.set("efr-tb-sab", require('./src/managers/inventory/efr-tb-sab-manager'));
inventoryMap.set("efr-tb-alt", require('./src/managers/inventory/efr-tb-alt-manager'));
inventoryMap.set("efr-hp-fng", require('./src/managers/inventory/efr-hp-fng-manager'));
inventoryMap.set("inv-ro-report", require('./src/managers/inventory/inv-ro-report-manager'));

var merchandiserMap = new Map();
merchandiserMap.set("efr-pk", require('./src/managers/merchandiser/efr-pk-manager'));
merchandiserMap.set("efr-pk-pbj", require('./src/managers/merchandiser/efr-pk-pbj-manager'));
merchandiserMap.set("efr-pk-pbr", require('./src/managers/merchandiser/efr-pk-pbr-manager'));
merchandiserMap.set("efr-pk-pba", require('./src/managers/merchandiser/efr-pk-pba-manager'));

module.exports = {
    auth: {
        AccountManager: require("./src/managers/auth/account-manager"),
        RoleManager: require("./src/managers/auth/role-manager")
    },
    inventory: {
        TransferInDocManager: inventoryMap.get("transfer-in-doc"),
        TransferOutDocManager: inventoryMap.get("transfer-out-doc"),
        InventoryManager: inventoryMap.get("inventory"),
        InventoryMovementManager: inventoryMap.get("inventory-movement"),
        FinishedGoodsManager: inventoryMap.get("efr-hp-fng"),
        ExpeditionsManager: inventoryMap.get("efr-kb-exp"),
        AlterationOutManager: inventoryMap.get("efr-kb-alt"),
        AlterationInManager: inventoryMap.get("efr-tb-alt"),
        TokoTransferStokManager: inventoryMap.get("efr-kb-rtt"),
        AdjustmentStockManager: inventoryMap.get("adjustment"),
        FinishingKirimBarangBaruManager: inventoryMap.get("efr-kb-fng"),
        PusatReturTokoKirimBarangReturManager: inventoryMap.get("efr-kb-rtf"),
        TokoKirimBarangReturnManager: inventoryMap.get("efr-kb-rtp"),
        ReturnKeUnitManager: inventoryMap.get("efr-kb-rtu"),
        FinishingKirimBarangReturSelesaiPerbaikanManager: inventoryMap.get("efr-kb-rtd"),
        FinishingTerimaAksesorisManager: inventoryMap.get("efr-tb-acc"),
        TokoTerimaAksesorisManager: inventoryMap.get("efr-tb-bat"),
        TokoTerimaBarangBaruManager: inventoryMap.get("efr-tb-bbt"),
        PusatTerimaBarangBaruManager: inventoryMap.get("efr-tb-bbp"),
        PusatBarangBaruTerimaBarangBaruManager: inventoryMap.get("efr-tb-bjb"),
        FinishingTerimaBarangReturManager: inventoryMap.get("efr-tb-bjr"),
        PusatReturTokoTerimaBarangReturSelesaiPerbaikanManager: inventoryMap.get("efr-tb-brd"),
        PusatReturTokoTerimaBarangReturManager: inventoryMap.get("efr-tb-brt"),
        FinishingTerimaKomponenManager: inventoryMap.get("efr-tb-sab"),
        TransferInDocExtManager: inventoryMap.get("transfer-in-doc-ext"),
        map: inventoryMap
    },
    merchandiser: {
        SPKManager: require('./src/managers/merchandiser/efr-pk-manager'),
        SPKBarangJadiManager: require('./src/managers/merchandiser/efr-pk-pbj-manager'),
        SPKBarangEmbalaseManager: require('./src/managers/merchandiser/efr-pk-pba-manager'),
        SPKBarangJadiReturManager: require('./src/managers/merchandiser/efr-pk-pbr-manager'),
        map: merchandiserMap
    },
    master: {
        ModuleManager: require('./src/managers/master/module-manager'),
        BankManager: require('./src/managers/master/bank-manager'),
        CardTypeManager: require('./src/managers/master/card-type-manager'),
        StoreManager: require('./src/managers/master/store-manager'),
        ItemManager: require('./src/managers/master/item-manager'),
        SupplierManager: require('./src/managers/master/supplier-manager'),
        StorageManager: require('./src/managers/master/storage-manager'),
        FinishedGoodsManager: require('./src/managers/master/finished-goods-manager'),
        MaterialManager: require('./src/managers/master/material-manager'),
        article: {
            ArticleMotifManager: require('./src/managers/master/article/article-motif-manager'),
            ArticleColorManager: require('./src/managers/master/article/article-color-manager')
        },
        ExpeditionServiceManager: require('./src/managers/master/expedition-service-manager')
    },
    sales: {
        SalesManager: require('./src/managers/sales/sales-manager'),
        SalesReturnManager: require('./src/managers/sales/sales-return-manager'),
        PromoManager: require('./src/managers/sales/promo-manager'),
        SalesReportManager: require('./src/managers/sales/report-manager')
    },

    etl: {
        itemsMigration: require('./src/etl/items-etl'),
        itemsSpMigration: require('./src/etl/sp-items-etl'),
        items: require('./src/etl/items-migration-etl'),
        storesMigration: require('./src/etl/stores-migration-etl'),
        storagesMigration: require('./src/etl/storages-migration-etl'),
        salesMigration: require('./src/etl/sales-etl'),
        salesSpMigration: require('./src/etl/sp-sales-etl'),
        factPenjualan: require('./src/etl/fact-penjualan'),
        factPenjualanSummary: require('./src/etl/fact-penjualan-summary'),
        dimBranch: require('./src/etl/dim-branch'),
        dimTime: require('./src/etl/dim-time')
    }

}

<commit_msg>uncomment adjustment manager<commit_after>var inventoryMap = new Map();
inventoryMap.set("transfer-in-doc-ext", require('./src/managers/inventory/transfer-in-doc-ext-manager'));
inventoryMap.set("transfer-in-doc", require('./src/managers/inventory/transfer-in-doc-manager'));
inventoryMap.set("transfer-out-doc", require('./src/managers/inventory/transfer-out-doc-manager'));
inventoryMap.set("inventory", require('./src/managers/inventory/inventory-manager'));
inventoryMap.set("inventory-movement", require('./src/managers/inventory/inventory-movement-manager'));

inventoryMap.set("efr-kb-rtt", require('./src/managers/inventory/efr-kb-rtt-manager'));
inventoryMap.set("adjustment", require('./src/managers/inventory/adjustment-manager'));
inventoryMap.set("efr-kb-fng", require('./src/managers/inventory/efr-kb-fng-manager'));
inventoryMap.set("efr-kb-rtf", require('./src/managers/inventory/efr-kb-rtf-manager'));
inventoryMap.set("efr-kb-rtp", require('./src/managers/inventory/efr-kb-rtp-manager'));
inventoryMap.set("efr-kb-rtu", require('./src/managers/inventory/efr-kb-rtu-manager'));
inventoryMap.set("efr-kb-rtd", require('./src/managers/inventory/efr-kb-rtd-manager'));
inventoryMap.set("efr-kb-exb", require('./src/managers/inventory/efr-kb-exb-manager'));
inventoryMap.set("efr-kb-exp", require('./src/managers/inventory/efr-kb-exp-manager'));
inventoryMap.set("efr-kb-alt", require('./src/managers/inventory/efr-kb-alt-manager'));
inventoryMap.set("efr-tb-act", require('./src/managers/inventory/efr-tb-act-manager'));
inventoryMap.set("efr-tb-bat", require('./src/managers/inventory/efr-tb-bat-manager'));
inventoryMap.set("efr-tb-bbp", require('./src/managers/inventory/efr-tb-bbp-manager'));
inventoryMap.set("efr-tb-bbt", require('./src/managers/inventory/efr-tb-bbt-manager'));
inventoryMap.set("efr-tb-bjb", require('./src/managers/inventory/efr-tb-bjb-manager'));
inventoryMap.set("efr-tb-bjr", require('./src/managers/inventory/efr-tb-bjr-manager'));
inventoryMap.set("efr-tb-brd", require('./src/managers/inventory/efr-tb-brd-manager'));
inventoryMap.set("efr-tb-brt", require('./src/managers/inventory/efr-tb-brt-manager'));
inventoryMap.set("efr-tb-sab", require('./src/managers/inventory/efr-tb-sab-manager'));
inventoryMap.set("efr-tb-alt", require('./src/managers/inventory/efr-tb-alt-manager'));
inventoryMap.set("efr-hp-fng", require('./src/managers/inventory/efr-hp-fng-manager'));
inventoryMap.set("inv-ro-report", require('./src/managers/inventory/inv-ro-report-manager'));

var merchandiserMap = new Map();
merchandiserMap.set("efr-pk", require('./src/managers/merchandiser/efr-pk-manager'));
merchandiserMap.set("efr-pk-pbj", require('./src/managers/merchandiser/efr-pk-pbj-manager'));
merchandiserMap.set("efr-pk-pbr", require('./src/managers/merchandiser/efr-pk-pbr-manager'));
merchandiserMap.set("efr-pk-pba", require('./src/managers/merchandiser/efr-pk-pba-manager'));

module.exports = {
    auth: {
        AccountManager: require("./src/managers/auth/account-manager"),
        RoleManager: require("./src/managers/auth/role-manager")
    },
    inventory: {
        TransferInDocManager: inventoryMap.get("transfer-in-doc"),
        TransferOutDocManager: inventoryMap.get("transfer-out-doc"),
        InventoryManager: inventoryMap.get("inventory"),
        InventoryMovementManager: inventoryMap.get("inventory-movement"),
        FinishedGoodsManager: inventoryMap.get("efr-hp-fng"),
        ExpeditionsManager: inventoryMap.get("efr-kb-exp"),
        AlterationOutManager: inventoryMap.get("efr-kb-alt"),
        AlterationInManager: inventoryMap.get("efr-tb-alt"),
        TokoTransferStokManager: inventoryMap.get("efr-kb-rtt"),
        AdjustmentStockManager: inventoryMap.get("adjustment"),
        FinishingKirimBarangBaruManager: inventoryMap.get("efr-kb-fng"),
        PusatReturTokoKirimBarangReturManager: inventoryMap.get("efr-kb-rtf"),
        TokoKirimBarangReturnManager: inventoryMap.get("efr-kb-rtp"),
        ReturnKeUnitManager: inventoryMap.get("efr-kb-rtu"),
        FinishingKirimBarangReturSelesaiPerbaikanManager: inventoryMap.get("efr-kb-rtd"),
        FinishingTerimaAksesorisManager: inventoryMap.get("efr-tb-acc"),
        TokoTerimaAksesorisManager: inventoryMap.get("efr-tb-bat"),
        TokoTerimaBarangBaruManager: inventoryMap.get("efr-tb-bbt"),
        PusatTerimaBarangBaruManager: inventoryMap.get("efr-tb-bbp"),
        PusatBarangBaruTerimaBarangBaruManager: inventoryMap.get("efr-tb-bjb"),
        FinishingTerimaBarangReturManager: inventoryMap.get("efr-tb-bjr"),
        PusatReturTokoTerimaBarangReturSelesaiPerbaikanManager: inventoryMap.get("efr-tb-brd"),
        PusatReturTokoTerimaBarangReturManager: inventoryMap.get("efr-tb-brt"),
        FinishingTerimaKomponenManager: inventoryMap.get("efr-tb-sab"),
        TransferInDocExtManager: inventoryMap.get("transfer-in-doc-ext"),
        map: inventoryMap
    },
    merchandiser: {
        SPKManager: require('./src/managers/merchandiser/efr-pk-manager'),
        SPKBarangJadiManager: require('./src/managers/merchandiser/efr-pk-pbj-manager'),
        SPKBarangEmbalaseManager: require('./src/managers/merchandiser/efr-pk-pba-manager'),
        SPKBarangJadiReturManager: require('./src/managers/merchandiser/efr-pk-pbr-manager'),
        map: merchandiserMap
    },
    master: {
        ModuleManager: require('./src/managers/master/module-manager'),
        BankManager: require('./src/managers/master/bank-manager'),
        CardTypeManager: require('./src/managers/master/card-type-manager'),
        StoreManager: require('./src/managers/master/store-manager'),
        ItemManager: require('./src/managers/master/item-manager'),
        SupplierManager: require('./src/managers/master/supplier-manager'),
        StorageManager: require('./src/managers/master/storage-manager'),
        FinishedGoodsManager: require('./src/managers/master/finished-goods-manager'),
        MaterialManager: require('./src/managers/master/material-manager'),
        article: {
            ArticleMotifManager: require('./src/managers/master/article/article-motif-manager'),
            ArticleColorManager: require('./src/managers/master/article/article-color-manager')
        },
        ExpeditionServiceManager: require('./src/managers/master/expedition-service-manager')
    },
    sales: {
        SalesManager: require('./src/managers/sales/sales-manager'),
        SalesReturnManager: require('./src/managers/sales/sales-return-manager'),
        PromoManager: require('./src/managers/sales/promo-manager'),
        SalesReportManager: require('./src/managers/sales/report-manager')
    },

    etl: {
        itemsMigration: require('./src/etl/items-etl'),
        itemsSpMigration: require('./src/etl/sp-items-etl'),
        items: require('./src/etl/items-migration-etl'),
        storesMigration: require('./src/etl/stores-migration-etl'),
        storagesMigration: require('./src/etl/storages-migration-etl'),
        salesMigration: require('./src/etl/sales-etl'),
        salesSpMigration: require('./src/etl/sp-sales-etl'),
        factPenjualan: require('./src/etl/fact-penjualan'),
        factPenjualanSummary: require('./src/etl/fact-penjualan-summary'),
        dimBranch: require('./src/etl/dim-branch'),
        dimTime: require('./src/etl/dim-time')
    }

}

<|endoftext|>


<commit_before>'use strict';

var walkSync = require('walk-sync');
var Plugin = require('broccoli-plugin');
var UglifyJS = require('uglify-es');
var path = require('path');
var fs = require('fs');
var defaults = require('lodash.defaultsdeep');
var symlinkOrCopy = require('symlink-or-copy');
var mkdirp = require('mkdirp');
var srcURL = require('source-map-url');
var MatcherCollection = require('matcher-collection');
var debug = require('debug')('broccoli-uglify-sourcemap');

module.exports = UglifyWriter;

UglifyWriter.prototype = Object.create(Plugin.prototype);
UglifyWriter.prototype.constructor = UglifyWriter;

const silent = process.argv.indexOf('--silent') !== -1;

function UglifyWriter (inputNodes, options) {
  if (!(this instanceof UglifyWriter)) {
    return new UglifyWriter(inputNodes, options);
  }

  inputNodes = Array.isArray(inputNodes) ? inputNodes : [inputNodes];

  Plugin.call(this, inputNodes, options);

  this.options = defaults(options, {
    uglify: {
      sourceMap: {},
    },
  });

  this.inputNodes = inputNodes;

  var exclude = this.options.exclude;
  if (Array.isArray(exclude)) {
    this.excludes = new MatcherCollection(exclude);
  } else {
    this.excludes = MatchNothing;
  }
}

var MatchNothing = {
  match: function () {
    return false;
  }
};

UglifyWriter.prototype.build = function () {
  var writer = this;

  this.inputPaths.forEach(function(inputPath) {
    walkSync(inputPath).forEach(function(relativePath) {
      if (relativePath.slice(-1) === '/') {
        return;
      }
      var inFile = path.join(inputPath, relativePath);
      var outFile = path.join(writer.outputPath, relativePath);

      mkdirp.sync(path.dirname(outFile));

      if (relativePath.slice(-3) === '.js' && !writer.excludes.match(relativePath)) {
        writer.processFile(inFile, outFile, relativePath, writer.outputPath);
      } else if (relativePath.slice(-4) === '.map') {
        if (writer.excludes.match(relativePath.slice(0, -4) + '.js')) {
          // ensure .map files for excldue JS paths are also copied forward
          symlinkOrCopy.sync(inFile, outFile);
        }
        // skip, because it will get handled when its corresponding JS does
      } else {
        symlinkOrCopy.sync(inFile, outFile);
      }
    });
  });

  return this.outputPath;
};

UglifyWriter.prototype.processFile = function(inFile, outFile, relativePath, outDir) {
  var src = fs.readFileSync(inFile, 'utf-8');
  var mapName = path.basename(outFile).replace(/\.js$/,'') + '.map';

  var mapDir;
  if (this.options.sourceMapDir) {
    mapDir = path.join(outDir, this.options.sourceMapDir);
  } else {
    mapDir = path.dirname(path.join(outDir, relativePath));
  }

  let options = defaults({}, this.options.uglify);
  if (options.sourceMap) {
    let filename = path.basename(inFile);
    let url = this.options.sourceMapDir ? '/' + path.join(this.options.sourceMapDir, mapName) : mapName;

    let sourceMap = { filename, url };

    if (srcURL.existsIn(src)) {
      let url = srcURL.getFrom(src);
      let sourceMapPath = path.join(path.dirname(inFile), url);
      if (fs.existsSync(sourceMapPath)) {
        sourceMap.content = JSON.parse(fs.readFileSync(sourceMapPath));
      } else if (!silent) {
        console.warn(`[WARN] (broccoli-uglify-sourcemap) "${url}" referenced in "${relativePath}" could not be found`);
      }
    }

    options = defaults(options, { sourceMap });
  }

  var start = new Date();
  debug('[starting]: %s %dKB', relativePath, (src.length / 1000));
  var result = UglifyJS.minify(src, options);
  var end = new Date();
  var total = end - start;
  debug('[finished]: %s %dKB in %dms', relativePath, (result.code.length / 1000), total);

  if (total > 20000 && !silent) {
    console.warn('[WARN] (broccoli-uglify-sourcemap) Minifying: `' + relativePath + '` took: ' + total + 'ms (more than 20,000ms)');
  }

  if (result.error) {
    result.error.filename = relativePath;
    throw result.error;
  }

  if (options.sourceMap) {
    var newSourceMap = JSON.parse(result.map);

    newSourceMap.sources = newSourceMap.sources.map(function(path){
      // If out output file has the same name as one of our original
      // sources, they will shadow eachother in Dev Tools. So instead we
      // alter the reference to the upstream file.
      if (path === relativePath) {
        path = path.replace(/\.js$/, '-orig.js');
      }
      return path;
    });
    mkdirp.sync(mapDir);
    fs.writeFileSync(path.join(mapDir, mapName), JSON.stringify(newSourceMap));
  }
  fs.writeFileSync(outFile, result.code);
};
<commit_msg>throw error before trying to read minified code length<commit_after>'use strict';

var walkSync = require('walk-sync');
var Plugin = require('broccoli-plugin');
var UglifyJS = require('uglify-es');
var path = require('path');
var fs = require('fs');
var defaults = require('lodash.defaultsdeep');
var symlinkOrCopy = require('symlink-or-copy');
var mkdirp = require('mkdirp');
var srcURL = require('source-map-url');
var MatcherCollection = require('matcher-collection');
var debug = require('debug')('broccoli-uglify-sourcemap');

module.exports = UglifyWriter;

UglifyWriter.prototype = Object.create(Plugin.prototype);
UglifyWriter.prototype.constructor = UglifyWriter;

const silent = process.argv.indexOf('--silent') !== -1;

function UglifyWriter (inputNodes, options) {
  if (!(this instanceof UglifyWriter)) {
    return new UglifyWriter(inputNodes, options);
  }

  inputNodes = Array.isArray(inputNodes) ? inputNodes : [inputNodes];

  Plugin.call(this, inputNodes, options);

  this.options = defaults(options, {
    uglify: {
      sourceMap: {},
    },
  });

  this.inputNodes = inputNodes;

  var exclude = this.options.exclude;
  if (Array.isArray(exclude)) {
    this.excludes = new MatcherCollection(exclude);
  } else {
    this.excludes = MatchNothing;
  }
}

var MatchNothing = {
  match: function () {
    return false;
  }
};

UglifyWriter.prototype.build = function () {
  var writer = this;

  this.inputPaths.forEach(function(inputPath) {
    walkSync(inputPath).forEach(function(relativePath) {
      if (relativePath.slice(-1) === '/') {
        return;
      }
      var inFile = path.join(inputPath, relativePath);
      var outFile = path.join(writer.outputPath, relativePath);

      mkdirp.sync(path.dirname(outFile));

      if (relativePath.slice(-3) === '.js' && !writer.excludes.match(relativePath)) {
        writer.processFile(inFile, outFile, relativePath, writer.outputPath);
      } else if (relativePath.slice(-4) === '.map') {
        if (writer.excludes.match(relativePath.slice(0, -4) + '.js')) {
          // ensure .map files for excldue JS paths are also copied forward
          symlinkOrCopy.sync(inFile, outFile);
        }
        // skip, because it will get handled when its corresponding JS does
      } else {
        symlinkOrCopy.sync(inFile, outFile);
      }
    });
  });

  return this.outputPath;
};

UglifyWriter.prototype.processFile = function(inFile, outFile, relativePath, outDir) {
  var src = fs.readFileSync(inFile, 'utf-8');
  var mapName = path.basename(outFile).replace(/\.js$/,'') + '.map';

  var mapDir;
  if (this.options.sourceMapDir) {
    mapDir = path.join(outDir, this.options.sourceMapDir);
  } else {
    mapDir = path.dirname(path.join(outDir, relativePath));
  }

  let options = defaults({}, this.options.uglify);
  if (options.sourceMap) {
    let filename = path.basename(inFile);
    let url = this.options.sourceMapDir ? '/' + path.join(this.options.sourceMapDir, mapName) : mapName;

    let sourceMap = { filename, url };

    if (srcURL.existsIn(src)) {
      let url = srcURL.getFrom(src);
      let sourceMapPath = path.join(path.dirname(inFile), url);
      if (fs.existsSync(sourceMapPath)) {
        sourceMap.content = JSON.parse(fs.readFileSync(sourceMapPath));
      } else if (!silent) {
        console.warn(`[WARN] (broccoli-uglify-sourcemap) "${url}" referenced in "${relativePath}" could not be found`);
      }
    }

    options = defaults(options, { sourceMap });
  }

  var start = new Date();
  debug('[starting]: %s %dKB', relativePath, (src.length / 1000));
  var result = UglifyJS.minify(src, options);
  var end = new Date();
  var total = end - start;
  if (total > 20000 && !silent) {
    console.warn('[WARN] (broccoli-uglify-sourcemap) Minifying: `' + relativePath + '` took: ' + total + 'ms (more than 20,000ms)');
  }

  if (result.error) {
    result.error.filename = relativePath;
    throw result.error;
  }

  debug('[finished]: %s %dKB in %dms', relativePath, (result.code.length / 1000), total);

  if (options.sourceMap) {
    var newSourceMap = JSON.parse(result.map);

    newSourceMap.sources = newSourceMap.sources.map(function(path){
      // If out output file has the same name as one of our original
      // sources, they will shadow eachother in Dev Tools. So instead we
      // alter the reference to the upstream file.
      if (path === relativePath) {
        path = path.replace(/\.js$/, '-orig.js');
      }
      return path;
    });
    mkdirp.sync(mapDir);
    fs.writeFileSync(path.join(mapDir, mapName), JSON.stringify(newSourceMap));
  }
  fs.writeFileSync(outFile, result.code);
};
<|endoftext|>