<commit_before>/**
 * Model migration manager - module for syncing models scheme with database tables.
 *
 */

module.exports = function(self,deps) {
    var _ = require('underscore');
    var crypto = require('crypto');
    var Q = require("q");
    var Sync = require('sql-ddl-sync').Sync;
    var g = require("grunt");
    var cfgPath = 'mysync/config.json';
    var rulePath = '../';
    var db;
    var scheme = {};
    var bdhash = {};
    var bdscheme = {};
    var magicBook = {};
    var full = true;
    var moduleErr;

    function difference(modelName, modelSch){
        var ret = {add:[], rm:[], chng:[], flagCreate: false};
        var bdSch = bdscheme[modelName];
        if(!bdSch){
            ret.flagCreate = true;
            ret.add = _.keys(modelSch);
            return ret;
        }
        var newAttrs = _.keys(modelSch);
        var bdAttrs = _.keys(bdSch);
        ret.add = _.difference(newAttrs, bdAttrs);
        ret.rm = _.difference(bdAttrs, newAttrs);
        var common = _.difference(newAttrs, ret.add);
        ret.chng = _.filter(common, function(key){
            // console.log([key, modelSch[key], bdSch[key]]);
            return !_.isEqual(modelSch[key], bdSch[key]);
        })
        return ret;
    }
    function calcHash(data) {
        var hash = crypto.createHash("md5");
        hash.update(data);
        return hash.digest('hex');
    }

    function save(modelname, properties) {
        bdhash[modelname] = calcHash(JSON.stringify(properties));
        bdscheme[modelname] = properties;
        g.file.write(cfgPath, JSON.stringify({hash:bdhash, scheme: bdscheme}));
        return true;
    }
    function isSynced(name) {
        if(calcHash(JSON.stringify(scheme[name])) == bdhash[name]) return true;
        else return false;
    }
    function syncOne(name, properties){
        // console.log(">>> Sync: " + name);
        var def = Q.defer();
        var sync = new Sync({
            dialect : db.driver_name,
            driver : db.driver,
            debug : function(text) {
                // console.log("> %s", text);
            }
        });
        sync.defineCollection(name, properties);
        sync.sync(function(err) {
            if(err) {
                // console.log(">>> Table: " + name + " > Sync Error: " + err);
                return def.reject(">>> Table: " + name + " > Sync Error: " + err);
            } else{
                save(name, properties);
                // console.log(">>> Table: " + name + " successfull synced.");
                def.resolve();
            }
        });
        return def.promise;
    }
    function magic(old){
        var df = Q.defer();
        // console.log("magic is ok");
        setTimeout(function(){df.resolve();}, 100);
        return df.promise;
    }
    function magicSyncOne(name) { //return promice
        // console.log(">>> magicSyncOne: "+name);
        var old = bdscheme[name];
        if(!old){
            return syncOne(name, scheme[name])
        }
        var def = Q.defer();
        var flagAdd = false;
        var cur = scheme[name];

        var stat = difference(name, scheme[name])
        var prms = def.promise,
            sch = old;
        // sync add
        if(stat.add.length != 0){
            sch = _.extend(old, _.pick(cur, stat.add));
            prms = prms.then(function(){ return syncOne(name, sch);});
        }
        // change
        if(stat.chng.length != 0){
           sch = _.extend(sch, _.pick(cur, stat.chng));
           flagChng = true;
        }
        //magic
         magic();
        // remove
        if(stat.rm.length != 0){
            var schR = _.omit(sch, stat.rm);
            if(_.isEqual(schR, cur)) prms = prms.then(function(){ return syncOne(name, cur);});
            // else console.log(">>> Internal error: before remove schemes not equal.")
        }else save(name, cur);

        setTimeout(function(){def.resolve()}, 100);
        return prms;
    }
    // if(g.option('file')){
        // try {
            // var val = require(rulePath + g.option('file'));
            // if(!val) {
                // console.log(">>> No rules in file: "+g.option('file')+" Add rules and run again.");
                // return done(false);
            // }
            // rules = val;
        // } catch (err) {
            // console.log(">>>" + err);
            // return done(false);
        // }
    // }
    function done(flag){
        // if(flag === false) console.log("<<< Migration module error: " + moduleErr);
        // else console.log("<<< ");
    }
    return {
        __init__: function() {
            //database
            db = m.cfg.db.default;
            //config: database scheme, hash
            if(g.file.exists(cfgPath)){
               var obj = g.file.readJSON(cfgPath);
               if(obj.hash) bdhash = obj.hash;
               if(obj.scheme) bdscheme = obj.scheme;
            } else {
                moduleErr = "Config not exists.";
                return done(false);
            }
            //application scheme
            for(var i in m.app.models) {
                scheme[i] = m.app.models[i].allProperties;
            }
            return deps.database.getDatabase("default").then(function(dbs){
                db = dbs;
                // console.log(db.driver_name);
            });
        },
        status : function(modelname) {
            // console.log(">>> Migration info:");
            var fullLog = [];
            function one(name){
                var onelog = "";
                if(!isSynced(name)) {
                    onelog = "Model: "+name+" not synced. ";
                    if(full){
                        var info = difference(name, scheme[name]);
                        if(info.flagCreate) {
                            onelog +="No such table in database.";
                            fullLog.push(onelog);
                            return false; }
                        if(info.add && info.add.length !=0 ) onelog +=("Add: "+ info.add);
                        if(info.chng && info.chng.length !=0 ) onelog +=(" Change: "+ info.chng);
                        if(info.rm && info.rm.length !=0 ) onelog +=(" Remove: "+ info.rm);
                    }
                    fullLog.push(onelog);
                    return false;
                } else {
                    fullLog.push("Model: "+name+" is synced.");
                    return true;
                }
            }
            if(modelname){
                if(scheme[modelname]) one(modelname);
                else {
                    // console.log("No model: "+modelname+" in application scheme.");
                    done(false);
                }
            }
            else {
                var need = 0;
                var all = 0;
                for(var i in scheme) {
                    all++;
                    var flag = one(i);
                    if(!flag) need++;
                }
                console.log("Need to sync: "+need+ " from "+ all+" models.");

            }
            if(fullLog.length != 0) console.log(fullLog);
            return done();
        },
        sync : function(modelname) {
            // console.log(">>> Migration auto sync:");
            if(modelname) {
                if(scheme[modelname]) {
                    if(isSynced(modelname)){
                        // console.log(">>> model " + modelname + " nothing to sync.");
                        return done();
                    }
                    var prms = syncOne(modelname, scheme[modelname]);
                    prms.done(done, function(){done(false);});
                } else {
                    // console.log("No model: "+modelname+" in application scheme.");
                    return done(false);
                }
            } else {
                var prms;
                _.keys(scheme).reduce(function(p,i){
                    if(!isSynced(i))
                        prms = p.then(function(){
                            return syncOne(i,scheme[i]);
                        });
                    else prms = p;
                    return prms
                },Q());
                prms.done(function() {
                    done();
                }, function() {
                    done(false);
                });
            }
        },
        createMagic: function(){
            // var txt = "module.exports = { /n";
//
            // txt += "/t"+name + ":function(oldScheme){/n"+
            // +"/t};/n"
            // txt += "}"
//
            // g.file.write(cfgPath, JSON.stringify({hash:bdhash, scheme: bdscheme}));
        },
        magicSync : function(modelname, filename){
            // console.log(">>> Migration magic sync:");
            if(modelname) {
                if(scheme[modelname]) {
                    if(isSynced(modelname)){
                        // console.log(">>> model " + modelname + " nothing to sync.");
                        return done();
                    }
                    // if(!rules[modelname]){
                        // console.log(">>> No rules for: " + modelname + " Add rules and run again. Or use sync:auto");
                        // return done(false);
                    // }

                    var prms = magicSyncOne(modelname);
                    prms.done(done, function(){done(false);});
                }
            } else {
                //TODO
                var prms;
                _.keys(scheme).reduce(function(p,i){
                    if(!isSynced(i))
                        prms = p.then(function(){
                            return magicSyncOne(i);
                        });
                    else prms = p;
                    return prms
                },Q());
                prms.done(function() {
                    done();
                }, function() {
                    done(false);
                });
            }
        }
    }
}

// function createMagic(obj){
//
// }
// function magicSyncOne(name, rules) { //return promice
    // console.log(">>> Rule sync : "+name);
    // var u = m.utils._;
    // var old = bdscheme[name];
    // if(!old){
        // return syncOne(name, scheme[name])
    // }
    // var def = Q.defer();
    // var flagAdd = false;
    // var cur = scheme[name];
    // var curK = u.keys(cur);
    // var oldK = u.keys(old);
    // var addK = u.difference(curK, oldK);
    // var remK = u.difference(oldK, curK);
    // var commonK = u.difference(curK, addK);
    // var changeK = u.filter(commonK, function(key){
        // return !u.isEqual(cur[key],old[key]);
    // })
    // console.log("   Add columns: "+ addK);
    // console.log("   Change columns: "+ changeK);
    // console.log("   Remove columns: "+ remK);
    // var prms = def.promise,
        // sch = old;
    // // sync add
    // if(addK.length != 0){
        // sch = u._.extend(old, u._.pick(cur, addK));
        // flagAdd = true;
    // }
    // // change
    // if(changeK.length != 0){
       // sch = u._.extend(sch, u._.pick(cur, changeK));
       // flagChng = true;
    // }
    // if(flagAdd) prms = prms.then(function(){ return syncOne(name, sch);});
    // //magic
//
    // // remove
    // if(remK.length != 0){
        // var schR = u._.omit(sch, remK);
        // if(u._.isEqual(schR, cur)) prms = prms.then(function(){ return syncOne(name, cur);});
        // else console.log(">>> Internal error: before remove schemes not equal.")
    // }else save(name, cur);
//
    // setTimeout(function(){def.resolve()}, 100);
    // return prms;
// }

function renameCols(modelname){
    var Dialect = require("./node_modules/sql-ddl-sync/lib/Dialects/" + db.driver_name);
    if(!Dialect) {
        console.log('Grunt error no dialect: ' + db.driver_name);
        return done(false);
    }
    Dialect.getCollectionProperties(db.driver, modelname, function(err, columns) {
            if(err) {
                console.log(err);
                return done(false);
            }
            console.log(columns);
        });
        function modifyOne(column){
           Dialect.modifyCollectionColumn(db.driver, modelname, column, function(err, obj) {
                if(err) {
                    console.log(err);
                    return done(false);
                }
                console.log(columns);
            });
        }

}

function nu_dialect() {
    if(!db) {
        console.log('Grunt error no database');
        return done(false);
    }
    var Dialect = require("./node_modules/sql-ddl-sync/lib/Dialects/" + db.driver_name);
    if(!Dialect) {
        console.log('Grunt error no dialect: ' + db.driver_name);
        return done(false);
    }
    var modelname = "subject";
    var properties = scheme[modelname];
    Dialect.hasCollection(db.driver, modelname, function(err, has) {
        if(err) {
            console.log(err);
            return done(false);
        }
        Dialect.getCollectionProperties(db.driver, modelname, function(err, columns) {
            if(err) {
                console.log(err);
                return done(false);
            }
            console.log(columns);
            console.log(properties);
            done();
        });
    });
}<commit_msg>init commit<commit_after>/**
 * Model migration manager - module for syncing models scheme with database tables.
 *
 */

module.exports = function(self,deps) {
    var _ = require('underscore');
    var crypto = require('crypto');
    var Q = require("q");
    var Sync = require('sql-ddl-sync').Sync;
    var g = require("grunt");
    var cfgPath = 'mysync/config.json';
    var rulePath = '../';
    var db;
    var scheme = {};
    var bdhash = {};
    var bdscheme = {};
    var magicBook = {};
    var full = true;
    var moduleErr;

    function difference(modelName, modelSch){
        var ret = {add:[], rm:[], chng:[], flagCreate: false};
        var bdSch = bdscheme[modelName];
        if(!bdSch){
            ret.flagCreate = true;
            ret.add = _.keys(modelSch);
            return ret;
        }
        var newAttrs = _.keys(modelSch);
        var bdAttrs = _.keys(bdSch);
        ret.add = _.difference(newAttrs, bdAttrs);
        ret.rm = _.difference(bdAttrs, newAttrs);
        var common = _.difference(newAttrs, ret.add);
        ret.chng = _.filter(common, function(key){
            // console.log([key, modelSch[key], bdSch[key]]);
            return !_.isEqual(modelSch[key], bdSch[key]);
        })
        return ret;
    }
    function calcHash(data) {
        var hash = crypto.createHash("md5");
        hash.update(data);
        return hash.digest('hex');
    }

    function save(modelname, properties) {
        bdhash[modelname] = calcHash(JSON.stringify(properties));
        bdscheme[modelname] = properties;
        g.file.write(cfgPath, JSON.stringify({hash:bdhash, scheme: bdscheme}));
        return true;
    }
    function isSynced(name) {
        if(calcHash(JSON.stringify(scheme[name])) == bdhash[name]) return true;
        else return false;
    }
    function syncOne(name, properties){
        console.log(">>> Sync: " + name);
        var def = Q.defer();
        var sync = new Sync({
            dialect : db.driver_name,
            driver : db.driver,
            debug : function(text) {
                console.log("> %s", text);
            }
        });
        sync.defineCollection(name, properties);
        sync.sync(function(err) {
            if(err) {
                console.log(">>> Table: " + name + " > Sync Error: " + err);
                return def.reject(">>> Table: " + name + " > Sync Error: " + err);
            } else{
                save(name, properties);
                console.log(">>> Table: " + name + " successfull synced.");
                def.resolve();
            }
        });
        return def.promise;
    }
    function magic(old){
        var df = Q.defer();
        console.log("magic is ok");
        setTimeout(function(){df.resolve();}, 100);
        return df.promise;
    }
    function magicSyncOne(name) { //return promice
        console.log(">>> magicSyncOne: "+name);
        var old = bdscheme[name];
        if(!old){
            return syncOne(name, scheme[name])
        }
        var def = Q.defer();
        var flagAdd = false;
        var cur = scheme[name];

        var stat = difference(name, scheme[name])
        var prms = def.promise,
            sch = old;
        // sync add
        if(stat.add.length != 0){
            sch = _.extend(old, _.pick(cur, stat.add));
            prms = prms.then(function(){ return syncOne(name, sch);});
        }
        // change
        if(stat.chng.length != 0){
           sch = _.extend(sch, _.pick(cur, stat.chng));
           flagChng = true;
        }
        //magic
         magic();
        // remove
        if(stat.rm.length != 0){
            var schR = _.omit(sch, stat.rm);
            if(_.isEqual(schR, cur)) prms = prms.then(function(){ return syncOne(name, cur);});
            else console.log(">>> Internal error: before remove schemes not equal.")
        }else save(name, cur);

        setTimeout(function(){def.resolve()}, 100);
        return prms;
    }
    // if(g.option('file')){
        // try {
            // var val = require(rulePath + g.option('file'));
            // if(!val) {
                // console.log(">>> No rules in file: "+g.option('file')+" Add rules and run again.");
                // return done(false);
            // }
            // rules = val;
        // } catch (err) {
            // console.log(">>>" + err);
            // return done(false);
        // }
    // }
    function done(flag){
        if(flag === false) console.log("<<< Migration module error: " + moduleErr);
        else console.log("<<< ");
    }
    return {
        __init__: function() {
            //database
            db = m.cfg.db.default;
            //config: database scheme, hash
            if(g.file.exists(cfgPath)){
               var obj = g.file.readJSON(cfgPath);
               if(obj.hash) bdhash = obj.hash;
               if(obj.scheme) bdscheme = obj.scheme;
            } else {
                moduleErr = "Config not exists.";
                return done(false);
            }
            //application scheme
            for(var i in m.app.models) {
                scheme[i] = m.app.models[i].allProperties;
            }
            return deps.database.getDatabase("default").then(function(dbs){
                db = dbs;
                console.log(db.driver_name);
            });
        },
        status : function(modelname) {
            console.log(">>> Migration info:");
            var fullLog = [];
            function one(name){
                var onelog = "";
                if(!isSynced(name)) {
                    onelog = "Model: "+name+" not synced. ";
                    if(full){
                        var info = difference(name, scheme[name]);
                        if(info.flagCreate) {
                            onelog +="No such table in database.";
                            fullLog.push(onelog);
                            return false; }
                        if(info.add && info.add.length !=0 ) onelog +=("Add: "+ info.add);
                        if(info.chng && info.chng.length !=0 ) onelog +=(" Change: "+ info.chng);
                        if(info.rm && info.rm.length !=0 ) onelog +=(" Remove: "+ info.rm);
                    }
                    fullLog.push(onelog);
                    return false;
                } else {
                    fullLog.push("Model: "+name+" is synced.");
                    return true;
                }
            }
            if(modelname){
                if(scheme[modelname]) one(modelname);
                else {
                    console.log("No model: "+modelname+" in application scheme.");
                    done(false);
                }
            }
            else {
                var need = 0;
                var all = 0;
                for(var i in scheme) {
                    all++;
                    var flag = one(i);
                    if(!flag) need++;
                }
                console.log("Need to sync: "+need+ " from "+ all+" models.");

            }
            if(fullLog.length != 0) console.log(fullLog);
            return done();
        },
        sync : function(modelname) {
            console.log(">>> Migration auto sync:");
            if(modelname) {
                if(scheme[modelname]) {
                    if(isSynced(modelname)){
                        console.log(">>> model " + modelname + " nothing to sync.");
                        return done();
                    }
                    var prms = syncOne(modelname, scheme[modelname]);
                    prms.done(done, function(){done(false);});
                } else {
                    console.log("No model: "+modelname+" in application scheme.");
                    return done(false);
                }
            } else {
                var prms;
                _.keys(scheme).reduce(function(p,i){
                    if(!isSynced(i))
                        prms = p.then(function(){
                            return syncOne(i,scheme[i]);
                        });
                    else prms = p;
                    return prms
                },Q());
                prms.done(function() {
                    done();
                }, function() {
                    done(false);
                });
            }
        },
        createMagic: function(){
            // var txt = "module.exports = { /n";
//
            // txt += "/t"+name + ":function(oldScheme){/n"+
            // +"/t};/n"
            // txt += "}"
//
            // g.file.write(cfgPath, JSON.stringify({hash:bdhash, scheme: bdscheme}));
        },
        magicSync : function(modelname, filename){
            console.log(">>> Migration magic sync:");
            if(modelname) {
                if(scheme[modelname]) {
                    if(isSynced(modelname)){
                        console.log(">>> model " + modelname + " nothing to sync.");
                        return done();
                    }
                    // if(!rules[modelname]){
                        // console.log(">>> No rules for: " + modelname + " Add rules and run again. Or use sync:auto");
                        // return done(false);
                    // }

                    var prms = magicSyncOne(modelname);
                    prms.done(done, function(){done(false);});
                }
            } else {
                //TODO
                var prms;
                _.keys(scheme).reduce(function(p,i){
                    if(!isSynced(i))
                        prms = p.then(function(){
                            return magicSyncOne(i);
                        });
                    else prms = p;
                    return prms
                },Q());
                prms.done(function() {
                    done();
                }, function() {
                    done(false);
                });
            }
        }
    }
}

function createMagic(obj){

}
function magicSyncOne(name, rules) { //return promice
    console.log(">>> Rule sync : "+name);
    var u = m.utils._;
    var old = bdscheme[name];
    if(!old){
        return syncOne(name, scheme[name])
    }
    var def = Q.defer();
    var flagAdd = false;
    var cur = scheme[name];
    var curK = u.keys(cur);
    var oldK = u.keys(old);
    var addK = u.difference(curK, oldK);
    var remK = u.difference(oldK, curK);
    var commonK = u.difference(curK, addK);
    var changeK = u.filter(commonK, function(key){
        return !u.isEqual(cur[key],old[key]);
    })
    console.log("   Add columns: "+ addK);
    console.log("   Change columns: "+ changeK);
    console.log("   Remove columns: "+ remK);
    var prms = def.promise,
        sch = old;
    // sync add
    if(addK.length != 0){
        sch = u._.extend(old, u._.pick(cur, addK));
        flagAdd = true;
    }
    // change
    if(changeK.length != 0){
       sch = u._.extend(sch, u._.pick(cur, changeK));
       flagChng = true;
    }
    if(flagAdd) prms = prms.then(function(){ return syncOne(name, sch);});
    //magic

    // remove
    if(remK.length != 0){
        var schR = u._.omit(sch, remK);
        if(u._.isEqual(schR, cur)) prms = prms.then(function(){ return syncOne(name, cur);});
        else console.log(">>> Internal error: before remove schemes not equal.")
    }else save(name, cur);

    setTimeout(function(){def.resolve()}, 100);
    return prms;
}

function renameCols(modelname){
    var Dialect = require("./node_modules/sql-ddl-sync/lib/Dialects/" + db.driver_name);
    if(!Dialect) {
        console.log('Grunt error no dialect: ' + db.driver_name);
        return done(false);
    }
    Dialect.getCollectionProperties(db.driver, modelname, function(err, columns) {
            if(err) {
                console.log(err);
                return done(false);
            }
            console.log(columns);
        });
        function modifyOne(column){
           Dialect.modifyCollectionColumn(db.driver, modelname, column, function(err, obj) {
                if(err) {
                    console.log(err);
                    return done(false);
                }
                console.log(columns);
            });
        }

}

function nu_dialect() {
    if(!db) {
        console.log('Grunt error no database');
        return done(false);
    }
    var Dialect = require("./node_modules/sql-ddl-sync/lib/Dialects/" + db.driver_name);
    if(!Dialect) {
        console.log('Grunt error no dialect: ' + db.driver_name);
        return done(false);
    }
    var modelname = "subject";
    var properties = scheme[modelname];
    Dialect.hasCollection(db.driver, modelname, function(err, has) {
        if(err) {
            console.log(err);
            return done(false);
        }
        Dialect.getCollectionProperties(db.driver, modelname, function(err, columns) {
            if(err) {
                console.log(err);
                return done(false);
            }
            console.log(columns);
            console.log(properties);
            done();
        });
    });
}<|endoftext|>


<commit_before>const assert = require('assert');
const memoryFS = require('memory-fs');
const cloneDeep = require('lodash.clonedeep');

const WebpackRequireFrom = require("../../");
const webpackConfigurations = require("./webpack.config.shared");

let appendChildTrap;

const createGlobalEnv = function () {
  // create micro browser-like environment for the tests
  global.setTimeout = () => {};
  global.window = {};
  global.document = {
    createElement: () => ({ src: {} }),
    getElementsByTagName: () => [{ appendChild: appendChildTrap }]
  };
  appendChildTrap = console.log;
}

const compile = (webpackEngine, config, fs) => {
  const compiler = webpackEngine(cloneDeep(config));
  compiler.outputFileSystem = fs;
  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err || stats.hasErrors()) {
        reject(new Error(err || stats.compilation.errors));
      }
      eval(fs.readFileSync(`${webpackConfigurations.buildPath}/main.js`).toString());
      resolve();
    })
  })
}

const compileWithWebpackVersion = (webpackVersion, configName) => compile(
  require(`../${webpackVersion}/node_modules/webpack`),
  webpackConfigurations[webpackVersion][configName],
  new memoryFS()
)

describe("webpack-require-from", function () {
  beforeEach(() => createGlobalEnv());

  it("throws when path and methodName are defined together", () => {
    try {
      new WebpackRequireFrom({ path: "some", methodName: "thing" })
      throw new Error("should throw when path and methodName are defined together")
    } catch (e) {}
  })
  Array.of("webpack2", "webpack3", "webpack4").map(webpackVersion =>
    describe(webpackVersion, () => [
      it("does nothing when config is empty", async () => {
        appendChildTrap = ({src}) => assert.strictEqual(src.split("/")[0], "originalPublicPath");
        await compileWithWebpackVersion(webpackVersion, "empty_pluginConf");
      }),
      it("does nothing when config is empty object", async () => {
        appendChildTrap = ({src}) => assert.strictEqual(src.split("/")[0], "originalPublicPath");
        await compileWithWebpackVersion(webpackVersion, "emptyObject_pluginConf");
      }),
      it("replaces with a static path", async () => {
        appendChildTrap = ({src}) => assert.strictEqual(src.split("/")[0], "staticPath");
        await compileWithWebpackVersion(webpackVersion, "path_pluginConf");
      }),
      it("replaces with a result of methodName", async () => {
        global.getPublicPath = () => 'newPublicPath/'
        appendChildTrap = ({src}) => assert.strictEqual(src.split("/")[0], "newPublicPath");
        await compileWithWebpackVersion(webpackVersion, "methodName_pluginConf");
        global.getPublicPath = undefined;
      }),
      it("replaces with result of replaceSrcMethodName", async () => {
        global.getSrc = (original) => `newSrc/${original}`
        appendChildTrap = ({src}) => {
          assert.strictEqual(src.split("/")[0], "newSrc");
          assert.strictEqual(src.split("/")[1], "originalPublicPath");
        }
        await compileWithWebpackVersion(webpackVersion, "replaceSrcMethodName_pluginConf");
        global.getSrc = undefined;
      }),
      it("replaces with result of methodName > replaceSrcMethodName", async () => {
        global.getPublicPath = () => 'newPublicPath/'
        global.getSrc = (original) => `newSrc/${original}`
        appendChildTrap = ({src}) => {
          assert.strictEqual(src.split("/")[0], "newSrc");
          assert.strictEqual(src.split("/")[1], "newPublicPath");
        }
        await compileWithWebpackVersion(webpackVersion, "replaceSrcMethodName_methodName_pluginConf");
        global.getSrc = global.getPublicPath = undefined;
      }),
      it("replaces with result of path > replaceSrcMethodName", async () => {
        global.getSrc = (original) => `newSrc/${original}`
        appendChildTrap = ({src}) => {
          assert.strictEqual(src.split("/")[0], "newSrc");
          assert.strictEqual(src.split("/")[1], "staticPath");
        }
        await compileWithWebpackVersion(webpackVersion, "replaceSrcMethodName_path_pluginConf");
        global.getSrc = global.getPublicPath = undefined;
      })
    ]
  )
  )
})<commit_msg>Add tests for missing methods<commit_after>const assert = require('assert');
const memoryFS = require('memory-fs');
const cloneDeep = require('lodash.clonedeep');

const WebpackRequireFrom = require("../../");
const webpackConfigurations = require("./webpack.config.shared");

let appendChildTrap;

const createGlobalEnv = function () {
  // create micro browser-like environment for the tests
  global.setTimeout = () => {};
  global.window = {};
  global.document = {
    createElement: () => ({ src: {} }),
    getElementsByTagName: () => [{ appendChild: appendChildTrap }]
  };
  appendChildTrap = console.log;
}

const compile = (webpackEngine, config, fs) => {
  const compiler = webpackEngine(cloneDeep(config));
  compiler.outputFileSystem = fs;
  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err || stats.hasErrors()) {
        reject(new Error(err || stats.compilation.errors));
      }
      eval(fs.readFileSync(`${webpackConfigurations.buildPath}/main.js`).toString());
      resolve();
    })
  })
}

const compileWithWebpackVersion = (webpackVersion, configName) => compile(
  require(`../${webpackVersion}/node_modules/webpack`),
  webpackConfigurations[webpackVersion][configName],
  new memoryFS()
)

describe("webpack-require-from", function () {
  beforeEach(() => createGlobalEnv());

  it("throws when path and methodName are defined together", () => {
    try {
      new WebpackRequireFrom({ path: "some", methodName: "thing" })
      throw new Error("should throw when path and methodName are defined together")
    } catch (e) {}
  })
  Array.of("webpack2", "webpack3", "webpack4").map(webpackVersion =>
    describe(webpackVersion, () => [
      it("does nothing when config is empty", async () => {
        appendChildTrap = ({src}) => assert.strictEqual(src.split("/")[0], "originalPublicPath");
        await compileWithWebpackVersion(webpackVersion, "empty_pluginConf");
      }),
      it("does nothing when config is empty object", async () => {
        appendChildTrap = ({src}) => assert.strictEqual(src.split("/")[0], "originalPublicPath");
        await compileWithWebpackVersion(webpackVersion, "emptyObject_pluginConf");
      }),
      it("replaces with a static path", async () => {
        appendChildTrap = ({src}) => assert.strictEqual(src.split("/")[0], "staticPath");
        await compileWithWebpackVersion(webpackVersion, "path_pluginConf");
      }),
      it("replaces with a result of methodName", async () => {
        global.getPublicPath = () => 'newPublicPath/'
        appendChildTrap = ({src}) => assert.strictEqual(src.split("/")[0], "newPublicPath");
        await compileWithWebpackVersion(webpackVersion, "methodName_pluginConf");
        global.getPublicPath = undefined;
      }),
      it("uses default public path when methodName is undefined", async () => {
        let originalConsoleError = console.error;
        console.error = () => {}
        global.getPublicPath = undefined;
        appendChildTrap = ({src}) => assert.strictEqual(src.split("/")[0], "originalPublicPath");
        await compileWithWebpackVersion(webpackVersion, "methodName_pluginConf");
        console.error = originalConsoleError;
      }),
      it("replaces with result of replaceSrcMethodName", async () => {
        global.getSrc = (original) => `newSrc/${original}`
        appendChildTrap = ({src}) => {
          assert.strictEqual(src.split("/")[0], "newSrc");
          assert.strictEqual(src.split("/")[1], "originalPublicPath");
        }
        await compileWithWebpackVersion(webpackVersion, "replaceSrcMethodName_pluginConf");
        global.getSrc = undefined;
      }),
      it("uses default public path when replaceSrcMethodName doesn't return a string", async () => {
        let originalConsoleError = console.error;
        console.error = () => {}
        global.getSrc = (original) => null
        appendChildTrap = ({src}) => {
          assert.strictEqual(src.split("/")[0], "originalPublicPath");
        }
        await compileWithWebpackVersion(webpackVersion, "replaceSrcMethodName_pluginConf");
        global.getSrc = undefined;
        console.error = originalConsoleError;
      }),
      it("uses default public  path when replaceSrcMethodName is undefined", async () => {
        let originalConsoleError = console.error;
        console.error = () => {}
        global.getSrc = undefined;
        appendChildTrap = ({src}) => {
          assert.strictEqual(src.split("/")[0], "originalPublicPath");
        }
        await compileWithWebpackVersion(webpackVersion, "replaceSrcMethodName_pluginConf");
        console.error = originalConsoleError;
      }),
      it("replaces with result of methodName > replaceSrcMethodName", async () => {
        global.getPublicPath = () => 'newPublicPath/'
        global.getSrc = (original) => `newSrc/${original}`
        appendChildTrap = ({src}) => {
          assert.strictEqual(src.split("/")[0], "newSrc");
          assert.strictEqual(src.split("/")[1], "newPublicPath");
        }
        await compileWithWebpackVersion(webpackVersion, "replaceSrcMethodName_methodName_pluginConf");
        global.getSrc = global.getPublicPath = undefined;
      }),
      it("replaces with result of path > replaceSrcMethodName", async () => {
        global.getSrc = (original) => `newSrc/${original}`
        appendChildTrap = ({src}) => {
          assert.strictEqual(src.split("/")[0], "newSrc");
          assert.strictEqual(src.split("/")[1], "staticPath");
        }
        await compileWithWebpackVersion(webpackVersion, "replaceSrcMethodName_path_pluginConf");
        global.getSrc = global.getPublicPath = undefined;
      })
    ]
  )
  )
})<|endoftext|>


<commit_before>// WebSync: Tables Plugin
// WebSync uses RequireJS for modules.
// define( [pluginName], [requiredModules], definition);
// pluginName is an optional argument that should only be used if the module is being bundled/loaded without RequireJS. It should match the path it's being required as.
define('/assets/tables.js',['edit','websync'],function(edit,websync){ var self = {};
    // Save all variables and information to the self object.

    // Plugins should use a jQuery namespace for ease of use.
	// Bind Example: $(document).bind("click.Tables", clickHandler);
	// Unbind Example: $("*").unbind(".Tables");
    $(".ribbon").append($('
<button class="btn" title="Delete Table"> Table</button>
<button class="btn" type="button" title="Insert Row Above"></button><button class="btn" type="button" title="Delete Row"> Row</button><button class="btn" type="button" title="Insert Row Below"></button>

<button class="btn" type="button" title="Insert Column Left"></button><button class="btn" type="button" title="Delete Column"> Column</button><button class="btn" type="button" title="Insert Column Right"></button>

'));
    $(".content").append($('

'));
    $("#Insert").append($('<button id="table" title="Table" class="btn Table"></button>'))
    $("#table").bind("click.Tables",function(e){
        console.log(e);
        var new_table = $("

")
        WebSync.insertAtCursor(new_table)
    });
	$('.Table [title="Insert Row Above"]').bind("click.Tables",function(e){
		if(self.selected){
			var html = "
";
			var size = self.tableSize();
			for(var i=0;i<size[0];i++){
				html+="	";
			}
			html+="
";
			$(html).insertBefore( self.selectedElem.parentElement);
			self.cursorMove(0,-1);
		}
	});
	$('.Table [title="Insert Row Below"]').bind("click.Tables",function(e){
		if(self.selected){
			var html = "
";
			var size = self.tableSize();
			for(var i=0;i<size[0];i++){
				html+="	";
			}
			html+="
";
			$(html).insertAfter( self.selectedElem.parentElement);
			self.cursorMove(0,1);
		}
	});
	$('.Table [title="Delete Row"]').bind("click.Tables",function(e){
		if(self.selected){
			self.selectedElem.parentElement.remove();
		}
		self.clearSelect();
	});
	$('.Table [title="Insert Column Left"]').bind("click.Tables",function(e){
		if(self.selected){
			var size = self.tableSize();
			var pos = self.selectedPos();
			for(var i=0;i<size[1];i++){
				$("	").insertBefore(self.selectedElem.parentElement.parentElement.children[i].children[pos[0]]);
			}
			self.cursorMove(-1,0);
		}
	});
	$('.Table [title="Insert Column Right"]').bind("click.Tables",function(e){
		if(self.selected){
			var size = self.tableSize();
			var pos = self.selectedPos();
			for(var i=0;i<size[1];i++){
				$("	").insertAfter(self.selectedElem.parentElement.parentElement.children[i].children[pos[0]]);
			}
			self.cursorMove(1,0);
		}
	});
	$('.Table [title="Delete Column"]').bind("click.Tables",function(e){
		if(self.selected){
			var size = self.tableSize();
			var pos = self.selectedPos();
			var parentElem = self.selectedElem.parentElement.parentElement
			for(var i=0;i<size[1];i++){
				parentElem.children[i].children[pos[0]].remove();
			}
			self.clearSelect();
		}
	});
	$('.Table [title="Delete Table"]').bind("click.Tables",function(e){
		if(self.selected){
			self.selectedElem.parentElement.parentElement.parentElement.remove();
			self.clearSelect();
		}
	});
    self.observer = new MutationObserver(function(mutations) {
        setTimeout(function(){
			self.cursorUpdate();
		},1);
    });
    $(".page").delegate("table","click.Tables",function(e){
        if(self.selectedElem.contentEditable!="true"){
            $('a:contains("Table")').click();
        }
        e.stopPropagation();
    });
    $(".page").delegate("td","mouseenter.Tables",function(e){
        if(self.selectionActive){
            self.selectionEnd = this;
            self.updateSelectedArea();
        }
    });
    $(".page").delegate("td","mouseleave.Tables",function(e){
    });
    $(".page").delegate("td","mousedown.Tables",function(e){
        if(this!=self.selectedElem){
            self.cursorSelect(this);
        }
        self.selectionActive=true;
        self.selectionEnd = null;
        self.updateSelectedArea();
        e.preventDefault();
    });
    $(".page").delegate("td","mouseup.Tables",function(e){
        self.selectionActive=false;
    });
    self.selectionActive = false;
    $(".page").bind("click.Tables",function(e){
        //console.log(e);
        self.clearSelect();
    });
    $(".content_well").delegate("td","contextmenu.Tables",function(e){
        if(this!=self.selectedElem){
            self.cursorSelect(this);
        }
        if(self.selectedElem.contentEditable!="true"){
            //e.preventDefault();
            //$(this).contextmenu();
        }
    });
    $(".content_well").delegate("td","dblclick.Tables",function(e){
		if(self.selectedElem.contentEditable!="true"){
			self.selectedEditable(true);
		}
    });
    $(".content_well").bind("keydown.Tables",function(e){
        //console.log(e);
        if(self.selectedElem){
            if(self.selected){ //&&!e.shiftKey){
                var editting = false;
                if(self.selectedElem.contentEditable){
                    editting=self.selectedElem.contentEditable=="true";
                }
                if(e.keyCode==13&&!e.shiftKey){
                    self.cursorMove(0,1);
                } else if(e.keyCode==9){
                    // Tab key
                    self.selectedEditable(false);
                    self.cursorMove(1-2*e.shiftKey,0);
                    e.preventDefault();
                } else if(e.keyCode==27){
                    // Escape
                    self.selectedEditable(false);
                } else if(e.keyCode==37&&!editting){
                    // Left arrow
                    self.cursorMove(-1,0);
                    e.preventDefault();
                }else if(e.keyCode==39&&!editting){
                    // Right arrow
                    self.cursorMove(1,0);
                    e.preventDefault();
                }else if(e.keyCode==38&&!editting){
                    // Up arrow
                    self.cursorMove(0,-1);
                    e.preventDefault();
                }else if(e.keyCode==40&&!editting){
                    // Down arrow
                    self.cursorMove(0,1);
                    e.preventDefault();
                } else {
                    if((!self.selectedElem.contentEditable||self.selectedElem.contentEditable=="inherit")&&_.indexOf([16,17,18,91,92],e.keyCode)==-1){
                        self.selectedEditable(true);

                        $(self.selectedElem).focus();
                        //WebSync.setCaretPosition(self.selectedElem,0);
                    }
                    setTimeout(self.cursorUpdate,1);
                }
            } else {
                if(!self.selectedElem.contentEditable||self.selectedElem.contentEditable=="false"){
                    self.selectedEditable(true);

                    $(self.selectedElem).focus();
                    //WebSync.setCaretPosition(self.selectedElem,0);
                }
            }
        }
    });

    WebSync.updateRibbon();
    $(".menu li a:contains('Table')").parent().hide();
	// Function: void [plugin=edit].disable();
    // Disables the plugin. This has to be set for possible plugin unloading.
	self.disable = function(){
		var elem = $(".Table").remove();
		WebSync.updateRibbon();
		$("*").unbind(".Tables");
		$("*").undelegate(".Tables");
	}
	// Helper methods:
	self.cursorSelect = function(td){
        $(".menu li a:contains('Table')").parent().fadeIn(200);
		// Cleanup last elem.
		if(self.selectedElem){
			self.selectedEditable(false);
		}
		document.getSelection().empty();
		self.selected = true;
		self.selectedElem = td;
		self.selectedEditable(false);
		self.cursorUpdate();
        self.observer.observe(self.selectedElem,{characterData:true});
	}
	self.cursorMove = function(dColumn, dRow){
		self.selectedEditable(false);
		var pos = self.selectedPos();
		var column = pos[0];
		var row = pos[1];
		if(self.selectedElem.parentElement.parentElement.children.length>row+dRow&&self.selectedElem.parentElement.parentElement.children[0].children.length>column+dColumn&&row+dRow>=0&&column+dColumn>=0){
			var new_td = self.selectedElem.parentElement.parentElement.children[row+dRow].children[column+dColumn];
			self.cursorSelect(new_td);
		}

	}
	self.cursorUpdate = function(){
		var pos = $(self.selectedElem).offset();
        pos.top += 1;
        pos.left += 1;
		$("#table_cursor").offset(pos).height($(self.selectedElem).height()).width($(self.selectedElem).width()+1).get(0).scrollIntoViewIfNeeded();
        self.updateSelectedArea();
	}
	self.selectedEditable = function(edit){
		if(!edit){
			self.selectedElem.contentEditable="inherit";
			$("#table_cursor").css({borderStyle: 'solid', outlineStyle: 'solid'});
			$('a:contains("Table")').click();
		}else{
			self.selectedElem.contentEditable=true;
			$("#table_cursor").css({borderStyle: 'dashed', outlineStyle: 'dashed'});
			$('a:contains("Text")').click();
			self.setEndOfContenteditable(self.selectedElem);
		}
	}
    self.clearSelect = function(){
		if(self.selected){
			self.selected = false;
			self.selectedEditable(false);
			$("#table_cursor").offset({left:-10000});
			delete self.selectedElem;
            $(".menu li a:contains('Table')").parent().fadeOut(200);
			$('a:contains("Text")').click();
            self.observer.disconnect();
            self.updateSelectedArea();
		}
	}
    self.updateSelectedArea = function(){
        if(self.selectedElem===self.selectionEnd||!self.selectionEnd||!self.selected){
            $("#table_selection").offset({left:-1000});
        }
        else {
            var pos = $(self.selectedElem).offset();
            var endPos = $(self.selectionEnd).offset();
            var baseWidth = $(self.selectionEnd).width();
            var baseHeight = $(self.selectionEnd).height();
            if(pos.left>endPos.left){
                var tmp_left = pos.left;
                pos.left = endPos.left;
                endPos.left = tmp_left;
                baseWidth = $(self.selectedElem).width();
            }
            if(pos.top>endPos.top){
                var tmp_top = pos.top;
                pos.top = endPos.top;
                endPos.top = tmp_top;
                baseHeight = $(self.selectedElem).height();
            }
            var height = endPos.top+baseHeight -pos.top;
            var width = endPos.left+baseWidth -pos.left;
            $("#table_selection").offset(pos).height(height).width(width);
            // Hidden selection area for copying.
            var range = rangy.createRange();
            range.selectNodeContents($("#table_clip").get(0));
            var sel = rangy.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    self.setEndOfContenteditable = function(contentEditableElement)
    {
        var range,selection;
        if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
        {
            range = document.createRange();//Create a range (a range is a like the selection but invisible)
            range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            selection = window.getSelection();//get the selection object (allows you to change selection)
            selection.removeAllRanges();//remove any selections already made
            selection.addRange(range);//make the range you have just created the visible selection
        }
        else if(document.selection)//IE 8 and lower
        {
            range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
            range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            range.select();//Select the range (make it the visible selection
        }
    }
	self.selectedPos = function(targetElem){
        var child = (targetElem||self.selectedElem);
		var column = 0;
		while( (child = child.previousSibling) != null )
			column++;
		child = (targetElem||self.selectedElem).parentElement
		var row = 0
		while( (child = child.previousSibling) != null )
			row++;
		return [column,row];
	}
	self.tableSize = function(){
		return [self.selectedElem.parentElement.children.length,self.selectedElem.parentElement.parentElement.children.length]
	}

    // Return self so other modules can hook into this one.
    return self;
});
<commit_msg>Updates<commit_after>// WebSync: Tables Plugin
// WebSync uses RequireJS for modules.
// define( [pluginName], [requiredModules], definition);
// pluginName is an optional argument that should only be used if the module is being bundled/loaded without RequireJS. It should match the path it's being required as.
define('/assets/tables.js',['edit','websync'],function(edit,websync){ var self = {};
    // Save all variables and information to the self object.

    // Plugins should use a jQuery namespace for ease of use.
	// Bind Example: $(document).bind("click.Tables", clickHandler);
	// Unbind Example: $("*").unbind(".Tables");
    $(".ribbon").append($('
<button class="btn" title="Delete Table"> Table</button>
<button class="btn" type="button" title="Insert Row Above"></button><button class="btn" type="button" title="Delete Row"> Row</button><button class="btn" type="button" title="Insert Row Below"></button>

<button class="btn" type="button" title="Insert Column Left"></button><button class="btn" type="button" title="Delete Column"> Column</button><button class="btn" type="button" title="Insert Column Right"></button>

'));
    $(".content").append($('

'));
    $("#Insert").append($('<button id="table" title="Table" class="btn Table"></button>'))
    $("#table").bind("click.Tables",function(e){
        console.log(e);
        var new_table = $("

")
        WebSync.insertAtCursor(new_table)
    });
	$('.Table [title="Insert Row Above"]').bind("click.Tables",function(e){
		if(self.selected){
			var html = "
";
			var size = self.tableSize();
			for(var i=0;i<size[0];i++){
				html+="	";
			}
			html+="
";
			$(html).insertBefore( self.selectedElem.parentElement);
			self.cursorMove(0,-1);
		}
	});
	$('.Table [title="Insert Row Below"]').bind("click.Tables",function(e){
		if(self.selected){
			var html = "
";
			var size = self.tableSize();
			for(var i=0;i<size[0];i++){
				html+="	";
			}
			html+="
";
			$(html).insertAfter( self.selectedElem.parentElement);
			self.cursorMove(0,1);
		}
	});
	$('.Table [title="Delete Row"]').bind("click.Tables",function(e){
		if(self.selected){
			self.selectedElem.parentElement.remove();
		}
		self.clearSelect();
	});
	$('.Table [title="Insert Column Left"]').bind("click.Tables",function(e){
		if(self.selected){
			var size = self.tableSize();
			var pos = self.selectedPos();
			for(var i=0;i<size[1];i++){
				$("	").insertBefore(self.selectedElem.parentElement.parentElement.children[i].children[pos[0]]);
			}
			self.cursorMove(-1,0);
		}
	});
	$('.Table [title="Insert Column Right"]').bind("click.Tables",function(e){
		if(self.selected){
			var size = self.tableSize();
			var pos = self.selectedPos();
			for(var i=0;i<size[1];i++){
				$("	").insertAfter(self.selectedElem.parentElement.parentElement.children[i].children[pos[0]]);
			}
			self.cursorMove(1,0);
		}
	});
	$('.Table [title="Delete Column"]').bind("click.Tables",function(e){
		if(self.selected){
			var size = self.tableSize();
			var pos = self.selectedPos();
			var parentElem = self.selectedElem.parentElement.parentElement
			for(var i=0;i<size[1];i++){
				parentElem.children[i].children[pos[0]].remove();
			}
			self.clearSelect();
		}
	});
	$('.Table [title="Delete Table"]').bind("click.Tables",function(e){
		if(self.selected){
			self.selectedElem.parentElement.parentElement.parentElement.remove();
			self.clearSelect();
		}
	});
    self.observer = new MutationObserver(function(mutations) {
        setTimeout(function(){
			self.cursorUpdate();
		},1);
    });
    $(".page").delegate("table","click.Tables",function(e){
        if(self.selectedElem.contentEditable!="true"){
            $('a:contains("Table")').click();
        }
        e.stopPropagation();
    });
    $(".page").delegate("td","mouseenter.Tables",function(e){
        if(self.selectionActive&&self.primaryTable()===self.primaryTable(this)){
            self.selectionEnd = this;
            self.updateSelectedArea();
        }
    });
    $(".page").delegate("td","mouseleave.Tables",function(e){
    });
    $(".page").delegate("td","mousedown.Tables",function(e){
        if(this!=self.selectedElem){
            self.cursorSelect(this);
        }
        self.selectionActive=true;
        self.selectionEnd = null;
        self.updateSelectedArea();
        e.preventDefault();
    });
    $(".page").delegate("td","mouseup.Tables",function(e){
        self.selectionActive=false;
    });
    self.selectionActive = false;
    $(".page").bind("click.Tables",function(e){
        //console.log(e);
        self.clearSelect();
    });
    $(".content_well").delegate("td","contextmenu.Tables",function(e){
        if(this!=self.selectedElem){
            self.cursorSelect(this);
        }
        if(self.selectedElem.contentEditable!="true"){
            //e.preventDefault();
            //$(this).contextmenu();
        }
    });
    $(".content_well").delegate("td","dblclick.Tables",function(e){
		if(self.selectedElem.contentEditable!="true"){
			self.selectedEditable(true);
		}
    });
    $(document).bind("paste.Tables",function(e){
        if(self.selected){
            console.log($(e.originalEvent.clipboardData.getData('text/html')));
        }
    });
    $(".content_well").bind("keydown.Tables",function(e){
        console.log(e);
        if(self.selectedElem){
            if(self.selected){ //&&!e.shiftKey){
                var editting = false;
                if(self.selectedElem.contentEditable){
                    editting=self.selectedElem.contentEditable=="true";
                }
                if(e.keyCode==13&&!e.shiftKey){
                    self.cursorMove(0,1);
                } else if(e.keyCode==9){
                    // Tab key
                    self.selectedEditable(false);
                    self.cursorMove(1-2*e.shiftKey,0);
                    e.preventDefault();
                } else if(e.keyCode==27){
                    // Escape
                    self.selectedEditable(false);
                } else if(e.keyCode==37&&!editting){
                    // Left arrow
                    self.cursorMove(-1,0);
                    e.preventDefault();
                }else if(e.keyCode==39&&!editting){
                    // Right arrow
                    self.cursorMove(1,0);
                    e.preventDefault();
                }else if(e.keyCode==38&&!editting){
                    // Up arrow
                    self.cursorMove(0,-1);
                    e.preventDefault();
                }else if(e.keyCode==40&&!editting){
                    // Down arrow
                    self.cursorMove(0,1);
                    e.preventDefault();
                } else {
                    if((!self.selectedElem.contentEditable||self.selectedElem.contentEditable=="inherit")&&_.indexOf([16,17,18,91,92],e.keyCode)==-1&&!(e.keyCode==67&&e.ctrlKey)){
                        self.selectedEditable(true);

                        $(self.selectedElem).focus();
                        //WebSync.setCaretPosition(self.selectedElem,0);
                    }
                    setTimeout(self.cursorUpdate,1);
                }
            } else {
                if(!self.selectedElem.contentEditable||self.selectedElem.contentEditable=="false"){
                    self.selectedEditable(true);

                    $(self.selectedElem).focus();
                    //WebSync.setCaretPosition(self.selectedElem,0);
                }
            }
        }
    });

    WebSync.updateRibbon();
    $(".menu li a:contains('Table')").parent().hide();
	// Function: void [plugin=edit].disable();
    // Disables the plugin. This has to be set for possible plugin unloading.
	self.disable = function(){
		var elem = $(".Table").remove();
		WebSync.updateRibbon();
		$("*").unbind(".Tables");
		$("*").undelegate(".Tables");
	}
	// Helper methods:
	self.cursorSelect = function(td){
        $(".menu li a:contains('Table')").parent().fadeIn(200);
		// Cleanup last elem.
		if(self.selectedElem){
			self.selectedEditable(false);
		}
		document.getSelection().empty();
		self.selected = true;
		self.selectedElem = td;
		self.selectedEditable(false);
		self.cursorUpdate();
        self.observer.observe(self.selectedElem,{characterData:true});
	}
	self.cursorMove = function(dColumn, dRow){
		self.selectedEditable(false);
		var pos = self.selectedPos();
		var column = pos[0];
		var row = pos[1];
		if(self.selectedElem.parentElement.parentElement.children.length>row+dRow&&self.selectedElem.parentElement.parentElement.children[0].children.length>column+dColumn&&row+dRow>=0&&column+dColumn>=0){
			var new_td = self.selectedElem.parentElement.parentElement.children[row+dRow].children[column+dColumn];
			self.cursorSelect(new_td);
		}

	}
	self.cursorUpdate = function(){
		var pos = $(self.selectedElem).offset();
        pos.top += 1;
        pos.left += 1;
		$("#table_cursor").offset(pos).height($(self.selectedElem).height()).width($(self.selectedElem).width()+1).get(0).scrollIntoViewIfNeeded();
        self.updateSelectedArea();
	}
	self.selectedEditable = function(edit){
		if(!edit){
			self.selectedElem.contentEditable="inherit";
			$("#table_cursor").css({borderStyle: 'solid', outlineStyle: 'solid'});
			$('a:contains("Table")').click();
		}else{
			self.selectedElem.contentEditable=true;
			$("#table_cursor").css({borderStyle: 'dashed', outlineStyle: 'dashed'});
			$('a:contains("Text")').click();
			self.setEndOfContenteditable(self.selectedElem);
		}
	}
    self.clearSelect = function(){
		if(self.selected){
			self.selected = false;
			self.selectedEditable(false);
			$("#table_cursor").offset({left:-10000});
			delete self.selectedElem;
            $(".menu li a:contains('Table')").parent().fadeOut(200);
			$('a:contains("Text")').click();
            self.observer.disconnect();
            self.selectedElem=null;
            self.updateSelectedArea();
		}
	}
    self.updateSelectedArea = function(){
        if(self.selectedElem===self.selectionEnd||!self.selectionEnd||!self.selected||self.primaryTable()!=self.primaryTable(self.selectionEnd)){
            $("#table_selection").hide();
        }
        else {
            var pos = $(self.selectedElem).offset();
            var endPos = $(self.selectionEnd).offset();
            var baseWidth = $(self.selectionEnd).width();
            var baseHeight = $(self.selectionEnd).height();
            if(pos.left>endPos.left){
                var tmp_left = pos.left;
                pos.left = endPos.left;
                endPos.left = tmp_left;
                baseWidth = $(self.selectedElem).width();
            }
            if(pos.top>endPos.top){
                var tmp_top = pos.top;
                pos.top = endPos.top;
                endPos.top = tmp_top;
                baseHeight = $(self.selectedElem).height();
            }
            var height = endPos.top+baseHeight -pos.top;
            var width = endPos.left+baseWidth -pos.left;
            $("#table_selection").show().offset(pos).height(height).width(width);
            // Set hidden selection area contents to mini-table.
            var selection_html = "

";
            var tpos_start = self.selectedPos();
            var tpos_end = self.selectedPos(self.selectionEnd);

            var top = tpos_start[1] < tpos_end[1] ? tpos_start[1] : tpos_end[1];
            var bottom = tpos_start[1] > tpos_end[1] ? tpos_start[1] : tpos_end[1];
            var left = tpos_start[0] < tpos_end[0] ? tpos_start[0] : tpos_end[0];
            var right = tpos_start[0] > tpos_end[0] ? tpos_start[0] : tpos_end[0];
            for(var y=top;y<=bottom;y++){
                selection_html+="
";
                for(var x=left;x<=right;x++){
                    selection_html+=""+self.selectedElem.parentElement.parentElement.children[y].children[x].innerHTML+"	";
                }
                selection_html+="
";
            }
            selection_html+="

";
            $("#table_clip").html(selection_html);
            // Hidden selection area for copying.
            var range = rangy.createRange();
            range.selectNodeContents($("#table_clip").get(0));
            var sel = rangy.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    self.setEndOfContenteditable = function(contentEditableElement)
    {
        var range,selection;
        if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
        {
            range = document.createRange();//Create a range (a range is a like the selection but invisible)
            range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            selection = window.getSelection();//get the selection object (allows you to change selection)
            selection.removeAllRanges();//remove any selections already made
            selection.addRange(range);//make the range you have just created the visible selection
        }
        else if(document.selection)//IE 8 and lower
        {
            range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
            range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
            range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
            range.select();//Select the range (make it the visible selection
        }
    }
    self.primaryTable = function(elem){
        return (elem||self.selectedElem).parentElement.parentElement.parentElement;
    }
	self.selectedPos = function(targetElem){
        var child = (targetElem||self.selectedElem);
		var column = 0;
		while( (child = child.previousSibling) != null )
			column++;
		child = (targetElem||self.selectedElem).parentElement
		var row = 0
		while( (child = child.previousSibling) != null )
			row++;
		return [column,row];
	}
	self.tableSize = function(){
		return [self.selectedElem.parentElement.children.length,self.selectedElem.parentElement.parentElement.children.length]
	}

    // Return self so other modules can hook into this one.
    return self;
});
<|endoftext|>


<commit_before>Package.describe({
  summary: "Generates the boilerplate html from program's manifest",
  version: '1.0.9'
});

Package.onUse(function (api) {
  api.use(['underscore',  'spacebars-compiler',
           'spacebars', 'htmljs', 'ui'], 'server');
  api.addFiles(['boilerplate-generator.js'], 'server');
  api.export(['Boilerplate'], 'server');
  // These are spacebars templates, but we process them manually with the
  // spacebars compiler rather than letting the 'templating' package (which
  // isn't fully supported on the server yet) handle it. That also means that
  // they don't contain the outer "<template>" tag.
  api.addAssets([
    'boilerplate_web.browser.html',
    'boilerplate_web.cordova.html'
  ], 'server');
});
<commit_msg>Add constraints to boilerplate-generator<commit_after>Package.describe({
  summary: "Generates the boilerplate html from program's manifest",
  version: '1.0.9'
});

Package.onUse(function (api) {
  api.use(['underscore',  'spacebars-compiler@1.0.12',
           'spacebars@1.0.12', 'htmljs@1.0.10', 'ui'], 'server');
  api.addFiles(['boilerplate-generator.js'], 'server');
  api.export(['Boilerplate'], 'server');
  // These are spacebars templates, but we process them manually with the
  // spacebars compiler rather than letting the 'templating' package (which
  // isn't fully supported on the server yet) handle it. That also means that
  // they don't contain the outer "<template>" tag.
  api.addAssets([
    'boilerplate_web.browser.html',
    'boilerplate_web.cordova.html'
  ], 'server');
});
<|endoftext|>


<commit_before>$.ninjaMessageOpen = function(customOptions){
  var options = $.extend({
    colors:$.ninjaColorsGet(),
    icon:null,
    id:null,
    onClose:function(){},
    onOpen:function(){},
    radius:$.ninjaRadius,
    seconds:0,
    text:null,
    title:null
  }, customOptions);
  var message = $(document.body).append('
').children('.ninjaMessage').attr('id', options.id).css({opacity:0.75}).append('

');
  var timer = null;
  if(options.seconds > 0){
    var milliseconds = options.seconds * 1000;
    timer = setTimeout(function(){
      $(message).ninjaMessageClose();
    }, milliseconds);
  };
  $(message).data({options:options});
  var handle = $('.ninjaMessageHandle', message).append('').css(options.colors.foreground);
  if(options.title){
    $(handle).text(options.title);
  };
  if(options.icon){
    if(options.title){
      $(handle).prepend(' ');
    };
    $(handle).prepend('');
    $('.ninjaMessageIcon', handle).ninjaIconCreate(options.icon).css({height:$(handle).height(), position:'relative', top:'-2px'});
  };
  $('.ninjaMessageClose', handle).ninjaButtonCreate({icon:'remove', onSelect:function(){
    $(message).ninjaMessageClose(timer);
  }}).ninjaRadius({radius:'0'});
  var content = $('.ninjaMessageContent', message).text(options.text).css(options.colors.foreground).ninjaRadius({corners:'bottom', radius:options.radius});
  $('.ninjaMessageReflection').css(options.colors.foreground).ninjaRadius({radius:options.radius}).position({
    at:'left bottom',
    of:message,
    my:'left top'
  }).css({opacity:0.125});
  $(document).keyup(function(event){
    if (event.keyCode == 27) { // esc key
      $(message).ninjaMessageClose(timer);
      $(document).unbind('keyup');
    }
  });
  $(message).position({
    at:'top',
    collision:'fit none',
    of:window,
    my:'top'
  }).slideDown('slow');
};

$.fn.ninjaMessageClose = function(timer){
  return this.each(function(i, message){
    clearTimeout(timer);
    var options = $(message).data().options;
    $(message).slideUp('slow', function() {
      options.onClose.call();
      $(message).remove();
    });
  });
};
<commit_msg>Prevents having title specified for messages removing the close button after it was added.<commit_after>$.ninjaMessageOpen = function(customOptions){
  var options = $.extend({
    colors:$.ninjaColorsGet(),
    icon:null,
    onClose:function(){},
    onOpen:function(){},
    radius:$.ninjaRadius,
    seconds:0,
    text:null,
    title:null
  }, customOptions);
  var message = $(document.body).append('
').find('.ninjaMessage').css({opacity:0.75}).append('

');
  var timer = null;
  if(options.seconds > 0){
    var milliseconds = options.seconds * 1000;
    timer = setTimeout(function(){
      $(message).ninjaMessageClose();
    }, milliseconds);
  };
  $(message).data({options:options});
  var handle = $('.ninjaMessageHandle', message).css(options.colors.foreground);
  if(options.title){
    $(handle).text(options.title);
  };
  if(options.icon){
    if(options.title){
      $(handle).prepend(' ');
    };
    $(handle).prepend('');
    $('.ninjaMessageIcon', handle).ninjaIconCreate(options.icon).css({height:$(handle).height(), position:'relative', top:'-2px'});
  };
  $(handle).append('');
  $('.ninjaMessageClose', handle).ninjaButtonCreate({icon:'remove', onSelect:function(){
    $(message).ninjaMessageClose(timer);
  }}).ninjaRadius({radius:'0'});
  var content = $('.ninjaMessageContent', message).text(options.text).css(options.colors.foreground).ninjaRadius({corners:'bottom', radius:options.radius});
  $('.ninjaMessageReflection').css(options.colors.foreground).ninjaRadius({radius:options.radius}).position({
    at:'left bottom',
    of:message,
    my:'left top'
  }).css({opacity:0.125});
  $(document).keyup(function(event){
    if (event.keyCode == 27) { // esc key
      $(message).ninjaMessageClose(timer);
      $(document).unbind('keyup');
    }
  });
  $(message).position({
    at:'top',
    collision:'fit none',
    of:window,
    my:'top'
  }).slideDown('slow');
};

$.fn.ninjaMessageClose = function(timer){
  return this.each(function(i, message){
    clearTimeout(timer);
    var options = $(message).data().options;
    $(message).slideUp('slow', function() {
      options.onClose.call();
      $(message).remove();
    });
  });
};
<|endoftext|>


<commit_before>/**
 * A simple plugin for Cordova to check if push is enabled on iOS.
 *
 * Developed by antonfire
 */

var AppLovinInit = function() {

};

/*
*	success - success callback
*	fail - error callback
*/
AppLovinInit.prototype.init = function(success, fail) {
  if (device.platform.toLowerCase() != 'ios') {
    success();
    return;
  }
  cordova.exec(success, fail, "PushEnabled", "checkStatus");
};
if(!window.plugins) {
    window.plugins = {};
}
if (!window.plugins.pushEnabled) {
    window.plugins.AppLovinInit = new AppLovinInit();
}

if (typeof module != 'undefined' && module.exports) {
  module.exports = AppLovinInit;
}
<commit_msg>Update AppLovinInit.js<commit_after>/**
 * A simple plugin for Cordova to check if push is enabled on iOS.
 *
 * Developed by antonfire
 */

var AppLovinInit = function() {

};

/*
*	success - success callback
*	fail - error callback
*/
AppLovinInit.prototype.init = function(success, fail) {
  if (device.platform.toLowerCase() != 'ios') {
    success();
    return;
  }
  cordova.exec(success, fail, "PushEnabled", "init");
};
if(!window.plugins) {
    window.plugins = {};
}
if (!window.plugins.pushEnabled) {
    window.plugins.AppLovinInit = new AppLovinInit();
}

if (typeof module != 'undefined' && module.exports) {
  module.exports = AppLovinInit;
}
<|endoftext|>


<commit_before>module('lively.tests.ModuleSystemTests').requires('lively.TestFramework').toRun(function() {

TestCase.subclass('lively.tests.ModuleSystemTests.ObjectLookupTest',
'running', {
    setUp: function() {
        delete lively.tests.ModuleSystemTests.foo;
        delete lively.tests.ModuleSystemTests.bar;
    }
},
'testing', {
    testLookupAndAssignObjectPath: function() {
        var context = lively.tests.ModuleSystemTests;
        this.assert(!context.foo, 'setup failed');
        this.assert(!context.bar, 'setup failed');
        this.assert(!lively.lookup("lively.tests.ModuleSystemTests.foo"), 'setup failed');

        var foo1 = context.foo = 'a';
        this.assertIdentity(foo1, lively.lookup("lively.tests.ModuleSystemTests.foo"), 'lookup 1');
        this.assertIdentity(foo1, lively.lookup("foo", context), 'lookup 2');

        var foo2 = 'b', assignResult = lively.assignObjectToPath(foo2, "foo", context);
        this.assertIdentity(foo2, assignResult, 'assignObjectToPath 1');
        this.assertIdentity(foo2, lively.lookup("foo", context), 'assignObjectToPath 2');
        lively.assignObjectToPath(foo1, "lively.tests.ModuleSystemTests.foo");
        this.assertIdentity(foo1, lively.lookup("foo", context), 'assignObjectToPath 3');
    }
});

TestCase.subclass('lively.tests.ModuleSystemTests.ModuleTest', {
    testGetModulesInDir: function() {
        var moduleNames, cb = URL.codeBase,
            url = cb.withFilename('foo/');
        this.mockClass(WebResource, 'getSubElements', function() {
            this.subDocuments = [cb.withFilename('foo/Foo.js').asWebResource(),
                                 cb.withFilename('foo/Bar.js').asWebResource()];
        });

        lively.Module.findAllInThenDo(url, function(modules) {
            moduleNames = modules.invoke('name');
        });
        this.assertMatches(['foo.Foo', 'foo.Bar'], moduleNames);
    },

    testGetModulesInDirWorksOnlyForDirectory: function() {
        var url = URL.codeBase.withFilename('foo');
        this.assertRaises(function() {
            lively.Module.findAllInThenDo(url, function() {});
        }, /foo is not a directory/, 'no error on non-dir URL');
    },
    testUriWithRealtivePath: function() {
        // FIXME this is for handling core in the namespace root
        var m = module('../users/robertkrahn/foo.js'),
            uri = m.uri(),
            expected = URL.root.withFilename('users/robertkrahn/foo.js').toString();
        this.assertEquals(expected, m.uri());
    },
    testRelativePathModule: function() {
        this.assertEquals(module('../users/robertkrahn/foo.js').uri(),
                          module('users/robertkrahn/foo.js').uri());
        this.assertEquals(module('users/robertkrahn/foo.js').uri(),
                          module('users.robertkrahn.foo').uri());
    },
    testToRun: function() {
        var moduleCodeExecuted = false;
        module('foo.goo').remove();
        module('foo.goo').requires().toRun(function() {
            moduleCodeExecuted = true;
        });
        this.assert(moduleCodeExecuted, 'module not executed');
    },
    testRequireLib: function() {
        var moduleCodeExecuted = false,
            lib = {uri: URL.root.withFilename('foo.js'), loadTest: function() { return false; }};
        module('foo.bar').requires().requiresLib(lib).toRun(function() {
            moduleCodeExecuted = true;
        });
        this.assert(!moduleCodeExecuted, 'module prematurely executed');
    }
});

AsyncTestCase.subclass('lively.tests.ModuleSystemTests.ModuleLoad',
'running', {
    setUp: function($super) {
        this.originalJSLoader = Global.JSLoader;
        Global.JSLoader = {
            loadJs: Functions.Null,
            isLoading: Functions.True,
            removeAllScriptsThatLinkTo: Functions.Null
        }
        $super();
    },
    tearDown: function($super) {
        Global.JSLoader = this.originalJSLoader;
        $super();
    }
},
'testing', {

    testRequireLib: function() {
        var moduleCodeExecuted = false,
            libBazIsLoaded = false,
            loadTestCalled = 0;
        module('foo.baz')
            .requires()
            .requiresLib({
                url: Config.codeBase + 'lib/baz.js',
                loadTest: function() { loadTestCalled++; return libBazIsLoaded; }
            }).toRun(function() {
                moduleCodeExecuted = true;
            });
        this.assert(module('foo.baz').hasPendingRequirements(), 'hasPendingRequirements 1');
        this.delay(function() {
            this.assert(loadTestCalled > 1, 'load test call count');
            this.assert(!moduleCodeExecuted, 'module prematurely executed');
            this.assert(module('foo.baz').hasPendingRequirements(), 'hasPendingRequirements 2');
            libBazIsLoaded = true;
        }, 60);
        this.delay(function() {
            this.assert(moduleCodeExecuted, 'module not executed');
            this.assert(!module('foo.baz').hasPendingRequirements(), 'hasPendingRequirements 3');
            this.done();
        }, 120);
    },

    testRequireLibSync: function() {
        var moduleCodeExecuted = false, libBazIsLoaded = false, libLoadCalled = 0, loadTestCalled = 0;
        module('foo.baz')
            .requires()
            .requiresLib({
                url: Config.codeBase + 'lib/baz.js',
                loadTest: function() { loadTestCalled++; return true;/*for sync loading the return value doesn't matter*/ },
                sync: true
            }).toRun(function() {
                moduleCodeExecuted = true;
            });
        module('foo.baz').load(true); // sync load
        // this.assertEquals(1, libLoadCalled, 'libLoad call count ' + libLoadCalled);
        this.assertEquals(0, loadTestCalled, 'loadTest call count ' + loadTestCalled);
        this.assert(moduleCodeExecuted, 'module body not loaded');
        this.assert(module('foo.baz').isLoaded(), 'module not loaded')
        this.done();
    },

    testRunAfterLoad: function() {
        var loadLogger = [];
        lively.module('foo.baz').remove();
        lively.module('foo.baz').runWhenLoaded(function() {debugger; loadLogger.push('whenLoaded callback'); });
        this.delay(function() {
            this.assertEquals([], loadLogger, 'no load before');
            this.assert(!module('foo.baz').isLoaded(), 'module already loaded?!');
            lively.module('foo.baz').requires().toRun(function() { loadLogger.push('module body'); });
        }, 20);
        this.delay(function() {
            this.assertEquals(['module body', 'whenLoaded callback'], loadLogger, 'after load callback not run');
            this.done();
        }, 60);
    }

});

});
<commit_msg>modules: allow utf chars in module names<commit_after>module('lively.tests.ModuleSystemTests').requires('lively.TestFramework').toRun(function() {

TestCase.subclass('lively.tests.ModuleSystemTests.ObjectLookupTest',
'running', {
    setUp: function() {
        delete lively.tests.ModuleSystemTests.foo;
        delete lively.tests.ModuleSystemTests.bar;
    }
},
'testing', {
    testLookupAndAssignObjectPath: function() {
        var context = lively.tests.ModuleSystemTests;
        this.assert(!context.foo, 'setup failed');
        this.assert(!context.bar, 'setup failed');
        this.assert(!lively.lookup("lively.tests.ModuleSystemTests.foo"), 'setup failed');

        var foo1 = context.foo = 'a';
        this.assertIdentity(foo1, lively.lookup("lively.tests.ModuleSystemTests.foo"), 'lookup 1');
        this.assertIdentity(foo1, lively.lookup("foo", context), 'lookup 2');

        var foo2 = 'b', assignResult = lively.assignObjectToPath(foo2, "foo", context);
        this.assertIdentity(foo2, assignResult, 'assignObjectToPath 1');
        this.assertIdentity(foo2, lively.lookup("foo", context), 'assignObjectToPath 2');
        lively.assignObjectToPath(foo1, "lively.tests.ModuleSystemTests.foo");
        this.assertIdentity(foo1, lively.lookup("foo", context), 'assignObjectToPath 3');
    }
});

TestCase.subclass('lively.tests.ModuleSystemTests.ModuleTest', {
    testGetModulesInDir: function() {
        var moduleNames, cb = URL.codeBase,
            url = cb.withFilename('foo/');
        this.mockClass(WebResource, 'getSubElements', function() {
            this.subDocuments = [cb.withFilename('foo/Foo.js').asWebResource(),
                                 cb.withFilename('foo/Bar.js').asWebResource()];
        });

        lively.Module.findAllInThenDo(url, function(modules) {
            moduleNames = modules.invoke('name');
        });
        this.assertMatches(['foo.Foo', 'foo.Bar'], moduleNames);
    },

    testGetModulesInDirWorksOnlyForDirectory: function() {
        var url = URL.codeBase.withFilename('foo');
        this.assertRaises(function() {
            lively.Module.findAllInThenDo(url, function() {});
        }, /foo is not a directory/, 'no error on non-dir URL');
    },

    testUriWithRealtivePath: function() {
        // FIXME this is for handling core in the namespace root
        var m = module('../users/robertkrahn/foo.js'),
            uri = m.uri(),
            expected = URL.root.withFilename('users/robertkrahn/foo.js').toString();
        this.assertEquals(expected, m.uri());
    },

    testRelativePathModule: function() {
        this.assertEquals(module('../users/robertkrahn/foo.js').uri(),
                          module('users/robertkrahn/foo.js').uri());
        this.assertEquals(module('users/robertkrahn/foo.js').uri(),
                          module('users.robertkrahn.foo').uri());
    },

    testToRun: function() {
        var moduleCodeExecuted = false;
        module('foo.goo').remove();
        module('foo.goo').requires().toRun(function() {
            moduleCodeExecuted = true;
        });
        this.assert(moduleCodeExecuted, 'module not executed');
    },

    testRequireLib: function() {
        var moduleCodeExecuted = false,
            lib = {uri: URL.root.withFilename('foo.js'), loadTest: function() { return false; }};
        module('foo.bar').requires().requiresLib(lib).toRun(function() {
            moduleCodeExecuted = true;
        });
        this.assert(!moduleCodeExecuted, 'module prematurely executed');
    },

    testModuleNamesSupportUnicodeChars: function() {
        this.assertEquals("Global.users.foo.config", module('users.foo.config').namespaceIdentifier);
        this.assertEquals("Global.users.föö.config", module('users.föö.config').namespaceIdentifier);
    }

});

AsyncTestCase.subclass('lively.tests.ModuleSystemTests.ModuleLoad',
'running', {
    setUp: function($super) {
        this.originalJSLoader = Global.JSLoader;
        Global.JSLoader = {
            loadJs: Functions.Null,
            isLoading: Functions.True,
            removeAllScriptsThatLinkTo: Functions.Null
        }
        $super();
    },
    tearDown: function($super) {
        Global.JSLoader = this.originalJSLoader;
        $super();
    }
},
'testing', {

    testRequireLib: function() {
        var moduleCodeExecuted = false,
            libBazIsLoaded = false,
            loadTestCalled = 0;
        module('foo.baz')
            .requires()
            .requiresLib({
                url: Config.codeBase + 'lib/baz.js',
                loadTest: function() { loadTestCalled++; return libBazIsLoaded; }
            }).toRun(function() {
                moduleCodeExecuted = true;
            });
        this.assert(module('foo.baz').hasPendingRequirements(), 'hasPendingRequirements 1');
        this.delay(function() {
            this.assert(loadTestCalled > 1, 'load test call count');
            this.assert(!moduleCodeExecuted, 'module prematurely executed');
            this.assert(module('foo.baz').hasPendingRequirements(), 'hasPendingRequirements 2');
            libBazIsLoaded = true;
        }, 60);
        this.delay(function() {
            this.assert(moduleCodeExecuted, 'module not executed');
            this.assert(!module('foo.baz').hasPendingRequirements(), 'hasPendingRequirements 3');
            this.done();
        }, 120);
    },

    testRequireLibSync: function() {
        var moduleCodeExecuted = false, libBazIsLoaded = false, libLoadCalled = 0, loadTestCalled = 0;
        module('foo.baz')
            .requires()
            .requiresLib({
                url: Config.codeBase + 'lib/baz.js',
                loadTest: function() { loadTestCalled++; return true;/*for sync loading the return value doesn't matter*/ },
                sync: true
            }).toRun(function() {
                moduleCodeExecuted = true;
            });
        module('foo.baz').load(true); // sync load
        // this.assertEquals(1, libLoadCalled, 'libLoad call count ' + libLoadCalled);
        this.assertEquals(0, loadTestCalled, 'loadTest call count ' + loadTestCalled);
        this.assert(moduleCodeExecuted, 'module body not loaded');
        this.assert(module('foo.baz').isLoaded(), 'module not loaded')
        this.done();
    },

    testRunAfterLoad: function() {
        var loadLogger = [];
        lively.module('foo.baz').remove();
        lively.module('foo.baz').runWhenLoaded(function() {debugger; loadLogger.push('whenLoaded callback'); });
        this.delay(function() {
            this.assertEquals([], loadLogger, 'no load before');
            this.assert(!module('foo.baz').isLoaded(), 'module already loaded?!');
            lively.module('foo.baz').requires().toRun(function() { loadLogger.push('module body'); });
        }, 20);
        this.delay(function() {
            this.assertEquals(['module body', 'whenLoaded callback'], loadLogger, 'after load callback not run');
            this.done();
        }, 60);
    }

});

});
<|endoftext|>


<commit_before>var RestAPI = function(){}

RestAPI.generateHerokuInstance = "https://wakanda-instance-generator.herokuapp.com/generate";
RestAPI.projects = "https://wakanda-instance-generator.herokuapp.com/projects";
RestAPI.registerUser = "https://wakanda-security.herokuapp.com/registerUser";
RestAPI.login = "https://wakanda-security.herokuapp.com/login";
RestAPI.fetchDashboardData = "fetchDashboardData";
RestAPI.statistics = "https://wakanda-statistic-receiver.com/statistics";<commit_msg>Fixing wakanda-statistic-receiver url to delete app data #closes 16<commit_after>var RestAPI = function(){}

RestAPI.generateHerokuInstance = "https://wakanda-instance-generator.herokuapp.com/generate";
RestAPI.projects = "https://wakanda-instance-generator.herokuapp.com/projects";
RestAPI.registerUser = "https://wakanda-security.herokuapp.com/registerUser";
RestAPI.login = "https://wakanda-security.herokuapp.com/login";
RestAPI.fetchDashboardData = "fetchDashboardData";
RestAPI.statistics = "https://wakanda-statistic-receiver.herokuapp.com/statistics";
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name camelcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/camelcase}
*/
setReadOnly( ns, 'camelcase', require( '@stdlib/string/base/camelcase' ) );

/**
* @name capitalize
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/capitalize}
*/
setReadOnly( ns, 'capitalize', require( '@stdlib/string/base/capitalize' ) );

/**
* @name constantcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/constantcase}
*/
setReadOnly( ns, 'constantcase', require( '@stdlib/string/base/constantcase' ) );

/**
* @name endsWith
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/ends-with}
*/
setReadOnly( ns, 'endsWith', require( '@stdlib/string/base/ends-with' ) );

/**
* @name formatInterpolate
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/format-interpolate}
*/
setReadOnly( ns, 'formatInterpolate', require( '@stdlib/string/base/format-interpolate' ) );

/**
* @name formatTokenize
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/format-tokenize}
*/
setReadOnly( ns, 'formatTokenize', require( '@stdlib/string/base/format-tokenize' ) );

/**
* @name kebabcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/kebabcase}
*/
setReadOnly( ns, 'kebabcase', require( '@stdlib/string/base/kebabcase' ) );

/**
* @name ltrim
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/left-trim}
*/
setReadOnly( ns, 'ltrim', require( '@stdlib/string/base/left-trim' ) );

/**
* @name lowercase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/lowercase}
*/
setReadOnly( ns, 'lowercase', require( '@stdlib/string/base/lowercase' ) );

/**
* @name pascalcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/pascalcase}
*/
setReadOnly( ns, 'pascalcase', require( '@stdlib/string/base/pascalcase' ) );

/**
* @name percentEncode
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/percent-encode}
*/
setReadOnly( ns, 'percentEncode', require( '@stdlib/string/base/percent-encode' ) );

/**
* @name replace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/replace}
*/
setReadOnly( ns, 'replace', require( '@stdlib/string/base/replace' ) );

/**
* @name rtrim
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/right-trim}
*/
setReadOnly( ns, 'rtrim', require( '@stdlib/string/base/right-trim' ) );

/**
* @name snakecase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/snakecase}
*/
setReadOnly( ns, 'snakecase', require( '@stdlib/string/base/snakecase' ) );

/**
* @name startcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/startcase}
*/
setReadOnly( ns, 'startcase', require( '@stdlib/string/base/startcase' ) );

/**
* @name startsWith
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/starts-with}
*/
setReadOnly( ns, 'startsWith', require( '@stdlib/string/base/starts-with' ) );

/**
* @name trim
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/trim}
*/
setReadOnly( ns, 'trim', require( '@stdlib/string/base/trim' ) );

/**
* @name uncapitalize
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/uncapitalize}
*/
setReadOnly( ns, 'uncapitalize', require( '@stdlib/string/base/uncapitalize' ) );

/**
* @name uppercase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/uppercase}
*/
setReadOnly( ns, 'uppercase', require( '@stdlib/string/base/uppercase' ) );

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name camelcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/camelcase}
*/
setReadOnly( ns, 'camelcase', require( '@stdlib/string/base/camelcase' ) );

/**
* @name capitalize
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/capitalize}
*/
setReadOnly( ns, 'capitalize', require( '@stdlib/string/base/capitalize' ) );

/**
* @name constantcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/constantcase}
*/
setReadOnly( ns, 'constantcase', require( '@stdlib/string/base/constantcase' ) );

/**
* @name endsWith
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/ends-with}
*/
setReadOnly( ns, 'endsWith', require( '@stdlib/string/base/ends-with' ) );

/**
* @name formatInterpolate
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/format-interpolate}
*/
setReadOnly( ns, 'formatInterpolate', require( '@stdlib/string/base/format-interpolate' ) );

/**
* @name formatTokenize
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/format-tokenize}
*/
setReadOnly( ns, 'formatTokenize', require( '@stdlib/string/base/format-tokenize' ) );

/**
* @name kebabcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/kebabcase}
*/
setReadOnly( ns, 'kebabcase', require( '@stdlib/string/base/kebabcase' ) );

/**
* @name ltrim
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/left-trim}
*/
setReadOnly( ns, 'ltrim', require( '@stdlib/string/base/left-trim' ) );

/**
* @name lowercase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/lowercase}
*/
setReadOnly( ns, 'lowercase', require( '@stdlib/string/base/lowercase' ) );

/**
* @name pascalcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/pascalcase}
*/
setReadOnly( ns, 'pascalcase', require( '@stdlib/string/base/pascalcase' ) );

/**
* @name percentEncode
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/percent-encode}
*/
setReadOnly( ns, 'percentEncode', require( '@stdlib/string/base/percent-encode' ) );

/**
* @name repeat
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/repeat}
*/
setReadOnly( ns, 'repeat', require( '@stdlib/string/base/repeat' ) );

/**
* @name replace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/replace}
*/
setReadOnly( ns, 'replace', require( '@stdlib/string/base/replace' ) );

/**
* @name rtrim
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/right-trim}
*/
setReadOnly( ns, 'rtrim', require( '@stdlib/string/base/right-trim' ) );

/**
* @name snakecase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/snakecase}
*/
setReadOnly( ns, 'snakecase', require( '@stdlib/string/base/snakecase' ) );

/**
* @name startcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/startcase}
*/
setReadOnly( ns, 'startcase', require( '@stdlib/string/base/startcase' ) );

/**
* @name startsWith
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/starts-with}
*/
setReadOnly( ns, 'startsWith', require( '@stdlib/string/base/starts-with' ) );

/**
* @name trim
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/trim}
*/
setReadOnly( ns, 'trim', require( '@stdlib/string/base/trim' ) );

/**
* @name uncapitalize
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/uncapitalize}
*/
setReadOnly( ns, 'uncapitalize', require( '@stdlib/string/base/uncapitalize' ) );

/**
* @name uppercase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/uppercase}
*/
setReadOnly( ns, 'uppercase', require( '@stdlib/string/base/uppercase' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>