<commit_before>"use strict";
var getvariables = require("./compile/variables");
var esprima = require("./esprima/index");
var esmangle = require("./esmangle/esmangle");
var escodegen = require("./escodegen/escodegen");
var typescript = require("./typescript/typescript");
var less = require("./less/less-node")();
less.PluginLoader = function () { };
var fs = require("fs");
var path = require("path");
var cwd = path.join(__dirname, "..");
module.exports = function commbuilder(buffer, filename, fullpath, watchurls) {
    var data = String(buffer);
    data = typescript.transpile(data);
    var code = esprima.parse(data);
    var {
        DeclaredVariables: declares,
        unDeclaredVariables: undeclares
    } = getvariables(code);
    var globals = Object.keys(undeclares);
    var globalsmap = {};
    globals.forEach(g => globalsmap[g] = g);
    var commName = filename.match(/([\$_\w][\w]*)\.[tj]sx?$/i);
    commName = commName && commName[1];
    var className = path.relative(cwd, fullpath).replace(/[\\\/\:\.]+/g, "-");
    if (commName) {
        //如果声明了main方法或main对象，默认用main作为返回值
        if (declares.main) {
            commName = "main";
        } else if (declares.Main) {
            commName = "Main";
        } else if (declares.MAIN) {
            commName = "MAIN";
        } else if (!declares[commName]) {
            commName = commName[0].toUpperCase() + commName.slice(1);
            if (!declares[commName]) {
                commName = null;
            }
        }
        var lessFile = fullpath.replace(/\.[jt]sx?$/i, ".less"),
            lessData;
        if (fs.existsSync(lessFile)) {
            watchurls.push(lessFile);
            if (fs.statSync(lessFile).isFile()) {
                watchurls.push(lessFile);
                less.render(`.${className}{${fs.readFileSync(lessFile).toString()}}`, {
                    compress: !process.env.IN_TEST_MODE
                }, function (err, data) {
                    if (err) return;
                    lessData = data.css;
                });
            }
        }
        if (lessData) {
            if (!declares.cless) {
                globalsmap.cless = "cless";
            } else {
                var random_variable;
                do {
                    random_variable = "cless_" + Math.random().toString(36)
                } while (declares[random_variable]);
                globalsmap.cless = random_variable;
            }
        }
    }
    var code_body;
    if (code.body.length === 1 && /(ExpressionStatement)$/.test(code.body[0].type)) {
        //如果整个函数只有一个表达式或一个变量，直接反回其本身
        code_body = [{
            "type": "ReturnStatement",
            "argument": lessData ? {
                "type": "CallExpression",
                "callee": {
                    "type": "Identifier",
                    "name": globalsmap.cless
                },
                "arguments": [
                    code.body[0].expression,
                    {
                        "type": "Literal",
                        "value": lessData,
                        "raw": JSON.stringify(lessData)
                    },
                    {
                        "type": "Literal",
                        "value": className,
                        "raw": JSON.stringify(className)
                    }
                ]
            } : code.body[0].expression
        }]
    } else {
        code_body = code.body.concat(commName ? {
            "type": "ReturnStatement",
            "argument": lessData ? {
                "type": "CallExpression",
                "callee": {
                    "type": "Identifier",
                    "name": globalsmap.cless
                },
                "arguments": [
                    {
                        "type": "Identifier",
                        "name": commName
                    },
                    {
                        "type": "Literal",
                        "value": lessData,
                        "raw": JSON.stringify(lessData)
                    },
                    {
                        "type": "Literal",
                        "value": className,
                        "raw": JSON.stringify(className)
                    }
                ]
            } : {
                    "type": "Identifier",
                    "name": commName
                }
        } : []);
    }
    globals = Object.keys(globalsmap);
    if (process.env.IN_TEST_MODE) {
        code = {
            "type": "Program",
            "sourceType": "script",
            body: code_body
        };
        data = escodegen.generate(code, {
            format: {
                renumber: true,
                hexadecimal: true, //十六进位
                escapeless: false,
                compact: false, //去空格
                semicolons: true, //分号
                parentheses: true //圆括号
            }
        });
        var params = globals.map(g => globalsmap[g]);
    } else {
        code = {
            type: "FunctionExpression",
            params: globals.map(n => ({
                type: "Identifier",
                name: globalsmap[n]
            })),
            body: {
                type: "BlockStatement",
                body: code_body
            },
            "generator": false,
            "expression": false
        }

        code = esmangle.optimize(code, null);
        code = esmangle.mangle(code);
        var params = code.params.map(id => id.name);
        code = {
            "type": "Program",
            "sourceType": "script",
            body: code.body.body
        };
        data = escodegen.generate(code, {
            format: {
                renumber: true,
                hexadecimal: true, //十六进位
                escapeless: true,
                compact: true, //去空格
                semicolons: false, //分号
                parentheses: false //圆括号
            }
        });
    }
    // console.log(data);
    var _arguments = [...globals, ...params].join();
    var length = (_arguments.length << 1).toString(36);
    if (length.length === 1) {
        length = "00" + length;
    } else if (length.length === 2) {
        length = "0" + length;
    }

    data = (_arguments.length ? length + _arguments : "") + data.replace(/[\u0100-\uffff]/g, m => "\\u" + (m.charCodeAt(0) > 0x1000 ? m.charCodeAt(0).toString(16) : 0 + m.charCodeAt(0).toString(16)));
    return data;
}<commit_msg>支持引用本项目及其他指定路径下的后端代码<commit_after>"use strict";
var getvariables = require("./compile/variables");
var esprima = require("./esprima/index");
var esmangle = require("./esmangle/esmangle");
var escodegen = require("./escodegen/escodegen");
var typescript = require("./typescript/typescript");
var less = require("./less/less-node")();
less.PluginLoader = function () { };
var fs = require("fs");
var path = require("path");
var cwd = path.join(__dirname, "..");
var useInternalReg = /^\s*(['"`])(?:(?:use|#?include)\b)?\s*(.*?)\1(\s*;)?\s*$/i;
module.exports = function commbuilder(buffer, filename, fullpath, watchurls) {
    var data = String(buffer);
    var commName = filename.match(/([\$_\w][\w]*)\.[tj]sx?$/i);
    commName = commName && commName[1];
    if (useInternalReg.test(data)) {
        data = data.replace(useInternalReg, function (match, quote, relative) {
            var realPath = path.relative(fullpath, relative);
            if (!fs.existsSync(realPath)) {
                realPath = relative;
            }
            if (!fs.existsSync(realPath)) {
                realPath = path.join(__dirname, "..", relative);
            } else {
                watchurls.push(realPath);
            }
            if (!fs.existsSync(realPath) || !fs.statSync(realPath).isFile()) {
                console.warn("没有处理include:" + filename);
                return match;
            }
            return fs.readFileSync(realPath).toString().replace(/\bmodule.exports\s*=/g, commName ? "var " + commName : "return ");
        });
    }
    data = typescript.transpile(data);
    var code = esprima.parse(data);
    var {
        DeclaredVariables: declares,
        unDeclaredVariables: undeclares
    } = getvariables(code);
    var globals = Object.keys(undeclares);
    var globalsmap = {};
    globals.forEach(g => globalsmap[g] = g);
    var className = path.relative(cwd, fullpath).replace(/[\\\/\:\.]+/g, "-");
    if (commName) {
        //如果声明了main方法或main对象，默认用main作为返回值
        if (declares.main) {
            commName = "main";
        } else if (declares.Main) {
            commName = "Main";
        } else if (declares.MAIN) {
            commName = "MAIN";
        } else if (!declares[commName]) {
            commName = commName[0].toUpperCase() + commName.slice(1);
            if (!declares[commName]) {
                commName = null;
            }
        }
        var lessFile = fullpath.replace(/\.[jt]sx?$/i, ".less"),
            lessData;
        if (fs.existsSync(lessFile)) {
            watchurls.push(lessFile);
            if (fs.statSync(lessFile).isFile()) {
                watchurls.push(lessFile);
                less.render(`.${className}{${fs.readFileSync(lessFile).toString()}}`, {
                    compress: !process.env.IN_TEST_MODE
                }, function (err, data) {
                    if (err) return;
                    lessData = data.css;
                });
            }
        }
        if (lessData) {
            if (!declares.cless) {
                globalsmap.cless = "cless";
            } else {
                var random_variable;
                do {
                    random_variable = "cless_" + Math.random().toString(36)
                } while (declares[random_variable]);
                globalsmap.cless = random_variable;
            }
        }
    }
    var code_body;
    if (code.body.length === 1 && /(ExpressionStatement)$/.test(code.body[0].type)) {
        //如果整个函数只有一个表达式或一个变量，直接反回其本身
        code_body = [{
            "type": "ReturnStatement",
            "argument": lessData ? {
                "type": "CallExpression",
                "callee": {
                    "type": "Identifier",
                    "name": globalsmap.cless
                },
                "arguments": [
                    code.body[0].expression,
                    {
                        "type": "Literal",
                        "value": lessData,
                        "raw": JSON.stringify(lessData)
                    },
                    {
                        "type": "Literal",
                        "value": className,
                        "raw": JSON.stringify(className)
                    }
                ]
            } : code.body[0].expression
        }]
    } else {
        code_body = code.body.concat(commName ? {
            "type": "ReturnStatement",
            "argument": lessData ? {
                "type": "CallExpression",
                "callee": {
                    "type": "Identifier",
                    "name": globalsmap.cless
                },
                "arguments": [
                    {
                        "type": "Identifier",
                        "name": commName
                    },
                    {
                        "type": "Literal",
                        "value": lessData,
                        "raw": JSON.stringify(lessData)
                    },
                    {
                        "type": "Literal",
                        "value": className,
                        "raw": JSON.stringify(className)
                    }
                ]
            } : {
                    "type": "Identifier",
                    "name": commName
                }
        } : []);
    }
    globals = Object.keys(globalsmap);
    if (process.env.IN_TEST_MODE) {
        code = {
            "type": "Program",
            "sourceType": "script",
            body: code_body
        };
        data = escodegen.generate(code, {
            format: {
                renumber: true,
                hexadecimal: true, //十六进位
                escapeless: false,
                compact: false, //去空格
                semicolons: true, //分号
                parentheses: true //圆括号
            }
        });
        var params = globals.map(g => globalsmap[g]);
    } else {
        code = {
            type: "FunctionExpression",
            params: globals.map(n => ({
                type: "Identifier",
                name: globalsmap[n]
            })),
            body: {
                type: "BlockStatement",
                body: code_body
            },
            "generator": false,
            "expression": false
        }

        code = esmangle.optimize(code, null);
        code = esmangle.mangle(code);
        var params = code.params.map(id => id.name);
        code = {
            "type": "Program",
            "sourceType": "script",
            body: code.body.body
        };
        data = escodegen.generate(code, {
            format: {
                renumber: true,
                hexadecimal: true, //十六进位
                escapeless: true,
                compact: true, //去空格
                semicolons: false, //分号
                parentheses: false //圆括号
            }
        });
    }
    // console.log(data);
    var _arguments = [...globals, ...params].join();
    var length = (_arguments.length << 1).toString(36);
    if (length.length === 1) {
        length = "00" + length;
    } else if (length.length === 2) {
        length = "0" + length;
    }

    data = (_arguments.length ? length + _arguments : "") + data.replace(/[\u0100-\uffff]/g, m => "\\u" + (m.charCodeAt(0) > 0x1000 ? m.charCodeAt(0).toString(16) : 0 + m.charCodeAt(0).toString(16)));
    return data;
}<|endoftext|>


<commit_before>'use strict';
const fs = require('fs');
module.exports = function (gameServer, args) {
var walkSync = function(dir, filelist) {

  if( dir[dir.length-1] != '/') dir=dir.concat('/')

  var fs = fs || require('fs'),
      files = fs.readdirSync(dir);
  filelist = filelist || [];
  files.forEach(function(file) {
    if (fs.statSync(dir + file).isDirectory()) {
      filelist = walkSync(dir + file + '/', filelist);
    }
    else {
      filelist.push(dir+file);
    }
  });
  return filelist;
};
var result = [];
var files = walkSync("./");

for (var i in files) {
if (files[i].indexOf("/node_modules/") != -1 || files[i].indexOf("/plugins/") != -1) continue;
  var file = fs.readFileSync(files[i],"utf8");
var startindex = 0;
for (;1==1;) {
 var index = file.indexOf("console.log(", startindex) + 12;
var ind = file.indexOf(")", index);
if (index == 11 || ind == -1) break;
startindex = ind;
result.push(file.substr(index, ind - index));
}
}
var final = "";
for (var i in result) {
  final = final + result[i] + "\n";
}
fs.writeFileSync("console.txt",final);
}
<commit_msg>Update consolelogfinder.js<commit_after>'use strict';
const fs = require('fs');
module.exports = function (gameServer, args) {
var walkSync = function(dir, filelist) {

  if( dir[dir.length-1] != '/') dir=dir.concat('/')

  var fs = fs || require('fs'),
      files = fs.readdirSync(dir);
  filelist = filelist || [];
  files.forEach(function(file) {
    if (fs.statSync(dir + file).isDirectory()) {
      filelist = walkSync(dir + file + '/', filelist);
    }
    else {
      filelist.push(dir+file);
    }
  });
  return filelist;
};
var result = [];
var files = walkSync("./");

for (var i in files) {
if (files[i].indexOf("/node_modules/") != -1 || files[i].indexOf("/plugins/") != -1) continue;
  var file = fs.readFileSync(files[i],"utf8");
var startindex = 0;
for (;1==1;) {
 var index = file.indexOf("console.log(", startindex) + 12;
var ind = file.indexOf(");", index);
if (index == 11 || ind == -1) break;
startindex = ind;
result.push(file.substr(index, ind - index));
}
}
var final = "";
for (var i in result) {
  final = final + result[i] + "\n";
}
fs.writeFileSync("console.txt",final);
}
<|endoftext|>


<commit_before>/**
 * Function to add a Slave to the HTML Page
 */
function addSlave (slaveObject, state) {
  if (!$('.' + slaveObject.id).length) {
    let serverName = 'Server ' + slaveObject.ip + ':' + slaveObject.port
    let slave = $('
').addClass('slave ' + slaveObject.id)
    let card = createHTMLCard(serverName, slaveObject)
    createHTMLHardware(serverName, slaveObject)
    $('#container1').append(card)
    toggleSlaves(state)
  }
}

function toggleSlaves (state) {
  if (!state) {
    $('.card').each(function (index, el) {
      $(this).append($('
').addClass('slave-disabled'))
    })
  } else {
    $('.card').each(function (index, el) {
      $(this).find('.slave-disabled').remove()
    })
  }
}

function createHTMLHardware (serverName, slaveObject) {
  let $slave = $('
').addClass('slave-' + slaveObject.id)
  let $icon = $('').addClass('ui disk outline icon')
  let $title = $('
').text(serverName).prepend($icon)
  setInterval(function () {
    $.getJSON('http://' + slaveObject.ip + ':' + slaveObject.port + '/hardware', (config, textStatus) => {
      let totalRAM = (config.totalmem / Math.pow(10, 9)).toFixed(2)
      let currentRAM = (config.freemem / Math.pow(10, 9)).toFixed(2)
      let percent = Math.round((currentRAM * 100) / totalRAM)
      if ($('.slave-' + slaveObject.id).length) {
        $slave = $('.slave-' + slaveObject.id)
        $slave.find('.cpu .bar').css('width', config.cpuUsage.toFixed(1) + '%')
        $slave.find('.cpu .bar .progress').text(config.cpuUsage.toFixed(1) + '%')
        $slave.find('.ram .bar').css('width', percent + '%')
        $slave.find('.ram .bar .progress').text(percent + '%')
      } else {
        let $cpu = $('
').addClass('ui green active progress cpu')
        $cpu.append($('
').attr('style', 'transition-duration: 300ms; width:' + config.cpuUsage.toFixed(1) + '%;')
              .addClass('bar')
              .append($('
').addClass('progress').text(config.cpuUsage.toFixed(0) + '%')))
        let $ram = $('
').addClass('ui orange active progress ram')
             .append($('
').attr('style', 'transition-duration: 300ms; width:' + percent + '%;')
                 .addClass('bar')
                 .append($('
').addClass('progress').text(percent + '%'))
             ).append($('
').addClass('label').text('Memory : ' + currentRAM + 'GB /' + totalRAM + 'GB'))

        $('#slaveContainer').append($slave.append())
        $('#slaveContainer').append(
          $slave.append(
            $title,
            $cpu.clone().append(
              $('
').addClass('label').text('CPU : ' + config.cpus[0].model + ' x' + config.cpus.length)
            ),
            $ram
          )
        )
      }
    })
  }, 2000)
}

function createHTMLCard (serverName, slave) {
  let slaveId = slave.ip + ':' + slave.port
  slaveId = slaveId.split('.').join('')
  slaveId = slaveId.split(':').join('')
  let $header = $('
').addClass('header')
  let $icon = $('').addClass('disk green outline icon')
  let $title = $('').text(slave.ip + ':' + slave.port)
  let $description = $('  <form class="ui form">' +
                            '
' +
                              '<input type="number" required class="iteration" placeholder="Number of iterations">' +
                            '
 ' +
                            '<input type="hidden" name="slaveId" value="' + slaveId + '">' +
                          '</form>' +
                          '
 $ >

')
  let $progressContainer = $('
').addClass('progressContainer-' + slaveId)
  let $body = $('
').append(changeStatus(slaveId, slave.status), $description)
  let stopButton = $('
').addClass('ui basic red button stop').prop('id', slaveId).text('Stop').append($('').addClass('window stop right icon'))
  let runButton = '
 Run
'
  let buttons = $('
').addClass('extra content center aligned grid').prop('id', 'action-' + slaveId).append(runButton).append(stopButton)
  stopButton.hide()
  $header.append($icon, $title)
  let $card = $('
').addClass('card ' + slave.id).append($('
').addClass('content').append($header, $body, $progressContainer)).append(buttons)
  return $card
}

function changeStatus (slaveId, status, progression) {
  let $status
  let $meta
  let $available = $('Available')
  let $executing = $('Executing')
  let $stopped = $('').addClass('ui tiny header red').text('Stopped').add($('').addClass('red unlinkify small icon'))
  let $analytics = $('').text('Check the statistics')
  switch (status) {
    case 'available':
      $status = changeMeta(slaveId, $available)
      break
    case 'executing':
      let $progressContainer = $('.progressContainer-' + slaveId)
      if ($('.progress.' + slaveId).length) {
        let $progress = $('.ui.active.progress.' + slaveId)
        $progress.children('.bar').css({
          'width': progression,
          'transition-duration': '300ms'
        })
        $progress.find('.progress').text(progression)
      } else {
        $status = changeMeta(slaveId, [$executing, $analytics])
        let $progress = $('
').addClass('ui active progress green ' + slaveId).attr('data-percent', progression)
        let $bar = $('
').addClass('bar')
        let $textProgress = $('
').addClass('progress').text('0%')
        let $label = $('
').addClass('label').text('Progression')

        $progressContainer.append($progress.append($bar.append($textProgress), $label))
      }
      $('.' + slaveId).find('.stop').fadeIn(400)
      $('.' + slaveId).find('.launch').fadeOut(400)
      break
    case 'finish':
      $meta = $('').addClass('ui tiny header green').text('Finished').add($('').addClass('green check small icon'))
      $('.progressContainer-' + slaveId).empty()
      $status = changeMeta(slaveId, [$meta, $analytics])
      $('.' + slaveId).find('.stop').fadeOut(400)
      $('.' + slaveId).find('.launch').fadeIn(400)
      break
    case 'stopped':
      $('.progressContainer-' + slaveId).empty()
      $status = changeMeta(slaveId, $stopped)
      $('.' + slaveId).find('.stop').fadeOut(400)
      $('.' + slaveId).find('.launch').fadeIn(400)
      break
    default:

  }

  return $status
}

function changeMeta (slaveId, $elements) {
  let $status
  if ($('#meta-' + slaveId).length) {
    $('#meta-' + slaveId).empty().append($elements)
  } else {
    $status = $('
').addClass('meta').prop('id', 'meta-' + slaveId).append($elements)
  }
  return $status
}
<commit_msg>Empeche le rafraichissement de la page lors d'un appui sur entrée dans les inputs<commit_after>/**
 * Function to add a Slave to the HTML Page
 */
function addSlave (slaveObject, state) {
  if (!$('.' + slaveObject.id).length) {
    let serverName = 'Server ' + slaveObject.ip + ':' + slaveObject.port
    let slave = $('
').addClass('slave ' + slaveObject.id)
    let card = createHTMLCard(serverName, slaveObject)
    createHTMLHardware(serverName, slaveObject)
    $('#container1').append(card)
    toggleSlaves(state)
  }
}

function toggleSlaves (state) {
  if (!state) {
    $('.card').each(function (index, el) {
      $(this).append($('
').addClass('slave-disabled'))
    })
  } else {
    $('.card').each(function (index, el) {
      $(this).find('.slave-disabled').remove()
    })
  }
}

function createHTMLHardware (serverName, slaveObject) {
  let $slave = $('
').addClass('slave-' + slaveObject.id)
  let $icon = $('').addClass('ui disk outline icon')
  let $title = $('
').text(serverName).prepend($icon)
  setInterval(function () {
    $.getJSON('http://' + slaveObject.ip + ':' + slaveObject.port + '/hardware', (config, textStatus) => {
      let totalRAM = (config.totalmem / Math.pow(10, 9)).toFixed(2)
      let currentRAM = (config.freemem / Math.pow(10, 9)).toFixed(2)
      let percent = Math.round((currentRAM * 100) / totalRAM)
      if ($('.slave-' + slaveObject.id).length) {
        $slave = $('.slave-' + slaveObject.id)
        $slave.find('.cpu .bar').css('width', config.cpuUsage.toFixed(1) + '%')
        $slave.find('.cpu .bar .progress').text(config.cpuUsage.toFixed(1) + '%')
        $slave.find('.ram .bar').css('width', percent + '%')
        $slave.find('.ram .bar .progress').text(percent + '%')
      } else {
        let $cpu = $('
').addClass('ui green active progress cpu')
        $cpu.append($('
').attr('style', 'transition-duration: 300ms; width:' + config.cpuUsage.toFixed(1) + '%;')
              .addClass('bar')
              .append($('
').addClass('progress').text(config.cpuUsage.toFixed(0) + '%')))
        let $ram = $('
').addClass('ui orange active progress ram')
             .append($('
').attr('style', 'transition-duration: 300ms; width:' + percent + '%;')
                 .addClass('bar')
                 .append($('
').addClass('progress').text(percent + '%'))
             ).append($('
').addClass('label').text('Memory : ' + currentRAM + 'GB /' + totalRAM + 'GB'))

        $('#slaveContainer').append($slave.append())
        $('#slaveContainer').append(
          $slave.append(
            $title,
            $cpu.clone().append(
              $('
').addClass('label').text('CPU : ' + config.cpus[0].model + ' x' + config.cpus.length)
            ),
            $ram
          )
        )
      }
    })
  }, 2000)
}

function createHTMLCard (serverName, slave) {
  let slaveId = slave.ip + ':' + slave.port
  slaveId = slaveId.split('.').join('')
  slaveId = slaveId.split(':').join('')
  let $header = $('
').addClass('header')
  let $icon = $('').addClass('disk green outline icon')
  let $title = $('').text(slave.ip + ':' + slave.port)
  let $description = $('  <form action="#" class="ui form">' +
                            '
' +
                              '<input type="number" required class="iteration" placeholder="Number of iterations">' +
                            '
 ' +
                            '<input type="hidden" name="slaveId" value="' + slaveId + '">' +
                          '</form>' +
                          '
 $ >

')
  let $progressContainer = $('
').addClass('progressContainer-' + slaveId)
  let $body = $('
').append(changeStatus(slaveId, slave.status), $description)
  let stopButton = $('
').addClass('ui basic red button stop').prop('id', slaveId).text('Stop').append($('').addClass('window stop right icon'))
  let runButton = '
 Run
'
  let buttons = $('
').addClass('extra content center aligned grid').prop('id', 'action-' + slaveId).append(runButton).append(stopButton)
  stopButton.hide()
  $header.append($icon, $title)
  let $card = $('
').addClass('card ' + slave.id).append($('
').addClass('content').append($header, $body, $progressContainer)).append(buttons)
  return $card
}

function changeStatus (slaveId, status, progression) {
  let $status
  let $meta
  let $available = $('Available')
  let $executing = $('Executing')
  let $stopped = $('').addClass('ui tiny header red').text('Stopped').add($('').addClass('red unlinkify small icon'))
  let $analytics = $('').text('Check the statistics')
  switch (status) {
    case 'available':
      $status = changeMeta(slaveId, $available)
      break
    case 'executing':
      let $progressContainer = $('.progressContainer-' + slaveId)
      if ($('.progress.' + slaveId).length) {
        let $progress = $('.ui.active.progress.' + slaveId)
        $progress.children('.bar').css({
          'width': progression,
          'transition-duration': '300ms'
        })
        $progress.find('.progress').text(progression)
      } else {
        $status = changeMeta(slaveId, [$executing, $analytics])
        let $progress = $('
').addClass('ui active progress green ' + slaveId).attr('data-percent', progression)
        let $bar = $('
').addClass('bar')
        let $textProgress = $('
').addClass('progress').text('0%')
        let $label = $('
').addClass('label').text('Progression')

        $progressContainer.append($progress.append($bar.append($textProgress), $label))
      }
      $('.' + slaveId).find('.stop').fadeIn(400)
      $('.' + slaveId).find('.launch').fadeOut(400)
      break
    case 'finish':
      $meta = $('').addClass('ui tiny header green').text('Finished').add($('').addClass('green check small icon'))
      $('.progressContainer-' + slaveId).empty()
      $status = changeMeta(slaveId, [$meta, $analytics])
      $('.' + slaveId).find('.stop').fadeOut(400)
      $('.' + slaveId).find('.launch').fadeIn(400)
      break
    case 'stopped':
      $('.progressContainer-' + slaveId).empty()
      $status = changeMeta(slaveId, $stopped)
      $('.' + slaveId).find('.stop').fadeOut(400)
      $('.' + slaveId).find('.launch').fadeIn(400)
      break
    default:

  }

  return $status
}

function changeMeta (slaveId, $elements) {
  let $status
  if ($('#meta-' + slaveId).length) {
    $('#meta-' + slaveId).empty().append($elements)
  } else {
    $status = $('
').addClass('meta').prop('id', 'meta-' + slaveId).append($elements)
  }
  return $status
}
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import WeekPicker from './WeekPicker';
import ActivityPicker from './ActivityPicker';
import SuitedForPicker from './SuitedForPicker';
import LoginModal from './LoginModal';
import ActivitiesContainer from './ActivitiesContainer';
import AllActivitiesContainer from './containers/AllActivitiesContainer';

//redux import
import { Provider } from "react-redux";
import store from "./store";

if (document.getElementById('activities')) {
    ReactDOM.render(
        <ActivitiesContainer/>,
        document.getElementById('activities')
    );
}

if (document.getElementById('week')) {
    ReactDOM.render(
        <WeekPicker/>,
        document.getElementById('week')
    );
}

if (document.getElementById('activityfilter')) {
    ReactDOM.render(
        <ActivityPicker/>,
        document.getElementById('activityfilter')
    );
}

if (document.getElementById('suitedfor')) {
    ReactDOM.render(
        <SuitedForPicker />,
        document.getElementById('suitedfor')
    );
}

if (document.getElementById('loginComponent')) {
    ReactDOM.render(
        <LoginModal />,
        document.getElementById('loginComponent')
    );
}

if (document.getElementById('allActivities')) {
    console.log("Hello from index");
    ReactDOM.render(
        <Provider store={store}>
            <AllActivitiesContainer />
        </Provider>, document.getElementById('allActivities')
    )
    console.log("bye from index");
}

<commit_msg>removed broken import statement after deleting loginModal<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import WeekPicker from './WeekPicker';
import ActivityPicker from './ActivityPicker';
import SuitedForPicker from './SuitedForPicker';
import ActivitiesContainer from './ActivitiesContainer';
import AllActivitiesContainer from './containers/AllActivitiesContainer';

//redux import
import { Provider } from "react-redux";
import store from "./store";

if (document.getElementById('activities')) {
    ReactDOM.render(
        <ActivitiesContainer/>,
        document.getElementById('activities')
    );
}

if (document.getElementById('week')) {
    ReactDOM.render(
        <WeekPicker/>,
        document.getElementById('week')
    );
}

if (document.getElementById('activityfilter')) {
    ReactDOM.render(
        <ActivityPicker/>,
        document.getElementById('activityfilter')
    );
}

if (document.getElementById('suitedfor')) {
    ReactDOM.render(
        <SuitedForPicker />,
        document.getElementById('suitedfor')
    );
}

if (document.getElementById('loginComponent')) {
    ReactDOM.render(
        <LoginModal />,
        document.getElementById('loginComponent')
    );
}

if (document.getElementById('allActivities')) {
    console.log("Hello from index");
    ReactDOM.render(
        <Provider store={store}>
            <AllActivitiesContainer />
        </Provider>, document.getElementById('allActivities')
    )
    console.log("bye from index");
}

<|endoftext|>


<commit_before>var _actions = {};

var action = function(description, callback) {
    if (callback === undefined) {
        //TODO: error logging like applebot
        _actions[description]();
    }
    else {
        _actions[description] = callback;
    }
};

var step = function(description, waitFunction, callback) {
    waitFunction();
    callback();
};

var runScript = function(client, appSettings) {

    action("Login", function(){
        client.url('https://play.google.com/apps/publish');
        client.setValue('#Email', appSettings.email, function(err, res) {

        });
        client.setValue('#Passwd', appSettings.password, function(err, res) {

        });
        client.submitForm('form#gaia_loginform', function(err, res) {

        });
    });

    action("Click on Add new app", function() {
        client.execute(function() {
            var spans = document.getElementsByTagName('span');
            correct_span = null;
            for(var i = 0; i < spans.length; i++) {
                var span = spans[i];
                if (span.innerHTML.trim() === "Add new application") {
                    correct_span = span;
                }
            }
        var buttonId = correct_span.parentElement.parentElement.id;
        document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });
    });

    step("Wait for first page", function() {
        client.waitFor('table tr a', TIMEOUT, function(err, res) {

        });
    }, function() {
            action("Click on Add new app");
    });

    action("Fill in and submit initial app information", function() {
        client.setValue(".popupContent .gwt-TextBox", appSettings.name, function(err, res) {

        });
        client.execute(function() {
            var divs = document.getElementsByTagName('div');
            var correct_div = null;
            for (var i = 0; i <divs.length; i++){
                var div = divs[i];
                if (div.innerHTML.trim() === "Upload APK"){
                    correct_div = div;
                }
            }
            var buttonId = correct_div.parentElement.id;
            document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });
    });

    step("Wait for app dialogue", function() {
        client.waitFor(".popupContent fieldset", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Fill in and submit initial app information");
    });

    action("Go to APK upload", function() {
        client.execute(function() {
            var divs = document.getElementsByTagName('div');
            matching_divs = [];

            for (var i = 0; i <divs.length; i++){
                var div = divs[i];
                if (div.innerHTML.trim() === "Upload your first APK to Production"){
                    matching_divs[matching_divs.length] = div;
                }
            }

            var correct_div = null;
            for (var i = 0; i <matching_divs.length ; i++){
                var div = matching_divs[i];
                if (div.parentElement.parentElement.children.length===3){
                    if (div.parentElement.parentElement.tagName === "DIV"){
                        correct_div = div;
                    }
                }
            }

            var buttonId = correct_div.parentElement.id;
            document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });

        client.execute(function(specialId) {
            var interval = window.setInterval(function() {
                var divs = document.getElementsByTagName('div');
                var correct_div = null;
                for (var i = 0; i <divs.length; i++){
                    var div = divs[i];
                    if (div.innerHTML.trim() === "Browse files"){
                        console.log("HIT");
                        correct_div = div;
                    }
                }

                var anyHit = false;
                if (correct_div) {
                    var nodes = correct_div.parentElement.parentElement.children;
                    for (var i =0; i <nodes.length; i++){
                        var node = nodes[i];
                        if (node.tagName==="INPUT"){
                            console.log("hit");
                            node.id= specialId;
                            node.addEventListener("change", function(e) {
                                console.log("NODE CHANGE");
                            });
                            anyHit = true;
                        }
                    }
                }

                if (anyHit) {
                    correct_div.innerHTML = "shit";
                    correct_div.id = "correct_div";
                    window.clearInterval(interval);
                }
            }, 1000);

        }, [specialId], function(err, res) {

        });
    });

    step("Wait for APK page", function() {
        client.waitFor("div[data-stickyscrolling-placeholder]", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Go to APK upload");
    });

    var upload_id = 'apk_uploading_id';

    action("Upload APK", function() {
        client.chooseFile("#" + specialId, appSettings.apk_path, function(err, res) {

        });

        client.execute(function(upload_id){
            var p = document.getElementsByTagName('p');
            for (i in p) {
                if (p[i].innerText.trim()==="Supported devices") {
                    p[i].parentElement.id = upload_id;
                    break;
                }
            }

        }, [upload_id]);
    });

    step("Wait for APK box", function() {
        client.waitFor("#correct_div", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Upload APK");
    });

    action("Go to Store Listing page", function() {
        client.execute(function(){
            var links =  document.getElementsByTagName('a');
            for (i in links){
                var link = links[i];
                if (link.innerText === "Store Listing"){
                    link.click();
                    break;
                }
            }
        });
    });

    step("Wait for APK upload", function() {
        client.waitForVisible('#' + upload_id, TIMEOUT * 10, function(err, res){

        });
    }, function() {
        action("Go to Store Listing page");
    });

    action("Fill in Store Listing information", function() {
        function searchForChild(parentTag, attribute, match, nested, childTag, childID, client){
            client.execute(function(parentTag, attribute, match, nested, childTag, childID) {
                var elements = document.querySelectorAll(parentTag);
                var correct_element = null;
                for(var i = 0; i < elements.length; i++) {
                    var element = elements[i];
                    if (element[attribute] === null) {}
                    else if (element[attribute].trim() === match) {
                        correct_element = element;
                    }
                }
                var i = 0;
                while (i < nested){
                    correct_element = correct_element.parentElement;
                    i++;
                }

                var child = correct_element.querySelector(childTag);
                child.id = childID;

            }, [parentTag, attribute, match, nested, childTag, childID]);

            return childID;
        }

        client.execute(function(){
            var textAreas = document.getElementsByTagName('textArea');
            textAreas[0].id = "textArea0Id";
            textAreas[1].id = "textArea1Id";

            var selectAreas = document.querySelectorAll('select');
            selectAreas[0].id = "selectArea0Id";
            selectAreas[1].id = "selectArea1Id";
            selectAreas[2].id = "selectArea2Id";
        });

        client.setValue("textarea#textArea0Id", appSettings.subtext, function(err, res){

        });

        client.setValue("textarea#textArea1Id", appSettings.promo, function(err,res){

        });

        client.click('#selectArea0Id option[value = ' + appSettings.category + ']');
        client.click('#selectArea1Id option[value = ' + appSettings.subcategory + ']');
        client.click('#selectArea2Id option[value = ' + appSettings.rating + ']');

        var promo_video_id = searchForChild('p', 'innerText', 'Promo Video', 2, 'input', 'promo_vid_child_id', client);
        var website_id = searchForChild('div', 'innerText', 'Website', 1, 'input', 'website_text_id', client);
        var email_id = searchForChild('div', 'innerText', 'Email', 1, 'input', 'email_text_id', client);
        var phone_id = searchForChild('div', 'innerText', 'Phone', 1, 'input', 'phone_text_id', client);
        var privacy_id = searchForChild('div', 'innerText' ,'Privacy Policy', 1, 'input', 'privacy_policy_id', client);

        client.setValue("#"+promo_video_id, appSettings.promo_vid, function(err, res){});
        client.setValue("#"+website_id, appSettings.website, function(err, res){});
        client.setValue("#"+email_id, appSettings.public_email, function(err, res){});
        client.setValue("#"+phone_id, appSettings.phone, function(err, res){});

        if (appSettings.privacy === null || appSettings.privacy === ""){
            client.execute(function(privacy_id){
                var elem = document.getElementById(privacy_id);
                var checkbox = elem.parentElement.querySelector('input[type="checkbox"]');
                checkbox.click();
            }, [privacy_id]);
        }
        else{
            client.setValue("#"+privacy_id, appSettings.privacy, function(err, res){});
        }
    });

    //not sure how to do this part
    action("Upload screenshots and graphics", function() {

    });

    action("Click save button", function() {
        this.execute(function(){
            var divs = document.querySelectorAll('div');
            correct_div = null;
            for (var i = 0; i <divs.length; i++){
                var div = divs[i];

                if (div.innerHTML.trim() === "Save"){
                    correct_div = div;
                }
            }
            correct_div.parentElement.click()
            correct_div.id = "documentSaved";

        });

        this.waitFor("#documentSaved", TIMEOUT, function(err,res){

        });

        this.execute(function(){
            var spans = document.querySelectorAll('span');

            for (var i in spans){
                var span = spans[i];

                if (span.innerText === "Your application has been saved."){
                    span.id = "documentCompletelySaved";
                }
            }
        });
    });

    step("Wait for Store Listing page", function() {
        client.waitFor('select', TIMEOUT, function(err, res){

            });
    }, function() {
        action("Fill in Store Listing information");
        action("Upload screenshots and graphics");
        action("Click save button");
    });

    action("Go to Pricing & Distribution page", function() {
        client.execute(function(){
            var links =  document.getElementsByTagName('a');
            for (i in links){
                var link = links[i];
                if (link.innerText === "Pricing & Distribution"){
                    link.click();
                    break;
                }
            }
        });
    });

    step("Wait for completely saved document", function() {
        this.waitFor("#documentCompletelySaved", TIMEOUT, function(err,res) {
        });
    }, function() {
        action("Go to Pricing & Distribution page");
    });

    action("Fill in Pricing & Distribution information - locations", function() {
        client.execute(function(listOfCountries){
            var toReturn = []

            var labels = document.querySelector('h4').parentElement.getElementsByTagName('label');
            for (var i in labels) {
                var label = labels[i];

                if (listOfCountries.indexOf(label.innerText) !== -1 ){
                    var input = label.querySelector('input');
                    if (input.id=== ""){
                        input.id = "languageToClickID" + i;
                    }
                    toReturn[toReturn.length] = input.id;
                }
            }

            for (language in toReturn){
                var elem = document.getElementById(toReturn[language]);
                elem.click();
            }
        }, [appSettings.locations]);
    });

    action("Fill in Pricing & Distribution information - education", function() {

        if (appSettings.education){
            client.execute(function(){
                var field = document.getElementsByTagName('fieldset')[1];
                field.querySelector('input').click();
            });

            client.waitFor('div.popupContent', TIMEOUT, function(err,res){

            });

            client.execute(function(ads, purchases){
                var divs = document.getElementsByTagName('div');
                for (i in divs){
                    var div = divs[i];
                    if (div.innerText === 'Continue'){
                        correct_div.parentElement.click();
                    }
                }

                var popUp = document.querySelector('div.popupContent');

                var inputs = popUp.getElementsByTagName('input');

                if (ads){
                    inputs[0].click();
                }
                else{
                    inputs[1].click();
                }
                if (purchases){
                    inputs[2].click();
                }
                else{
                    inputs[3].click();
                }

                var buttons = popUp.getElementsByTagName('button');
                for (i in buttons){
                    var button = buttons[i];
                    if (button.innerText.trim() === 'Save'){
                        button.click();
                        break;
                    }
                }

            }, [appSettings.education_ads, appSettings.education_purchases]);
        }
    });

    action("Fill in Pricing & Distribution information - opt in", function() {
        client.execute(function(optInValues){
            toReturn = [];
            var field = document.querySelectorAll('fieldset')[2];
            for (i in field.children){
                var child = field.children[i];
                if (child.tagName === "LABEL"){
                    if (optInValues[i]){
                        var input = child.querySelector('input');
                        if (input.id === ""){
                            input.id = "optInButtonToClickID" + child;
                        }
                        toReturn[toReturn.length] = input.id;
                    }
                }
            }

            for (opt in toReturn){
                var elem = document.getElementById(toReturn[opt]);
                elem.click();
            }

        }, [ [appSettings.marketing_opt_out, appSettings.content_guidelines, appSettings.us_export_laws] ]);
    });

    step("Wait for Pricing & Distribution page", function() {
        client.waitFor('colgroup', TIMEOUT, function(err, res){

        });
    }, function() {
        action("Fill in Pricing & Distribution information - locations");
        action("Fill in Pricing & Distribution information - education");
        action("Fill in Pricing & Distribution information - opt in");
        action("Click save button");
    });

    step("Wait for completely saved document", function() {
        this.waitFor("#documentCompletelySaved", TIMEOUT, function(err,res) {

        });
    }, function() {

    });

}

var ScriptRunner = {
    run: function(namespace, action, userOptions) {
        console.log("running " + namespace + ":" + action + " with " + JSON.stringify(userOptions));

        startSelenium(function(client) {

            var selenium = require('selenium-standalone');
            var seleniumServer = selenium({stdio: 'pipe'});

            seleniumServer.stdout.on('data', function(output) {
                var val = output.toString().trim();
                console.log(val);
                if(val.indexOf('jetty.jetty.Server')>-1){
                    client = client.init();
                    start();
                }
            });

            seleniumServer.stderr.on('data', function (data) {
              console.log('stderr: ' + data);
            });

            seleniumServer.on('close', function (code) {
              console.log('child process exited with code ' + code);
            });

            function start() {
                runScript(client, userOptions);
            }

        });
    },
    startSelenium: function(callback) {

        var webdriverjs = require('webdriverjs');
        var driverOptions = {
            desiredCapabilities: {
                browserName: 'chrome'
            }
        };
        var client = webdriverjs.remote(driverOptions);

        callback(client);
    }
};

exports = module.exports = ScriptRunner;
<commit_msg>reorganized runScript function<commit_after>var _actions = {};

var action = function(description, callback) {
    if (callback === undefined) {
        //TODO: error logging like applebot
        _actions[description]();
    }
    else {
        _actions[description] = callback;
    }
};

var step = function(description, waitFunction, callback) {
    waitFunction();
    callback();
};

var runScript = function(client, appSettings) {

    action("Login", function(){
        client.url('https://play.google.com/apps/publish');
        client.setValue('#Email', appSettings.email, function(err, res) {

        });
        client.setValue('#Passwd', appSettings.password, function(err, res) {

        });
        client.submitForm('form#gaia_loginform', function(err, res) {

        });
    });

    step("Log in to page", function() {

    }, function() {
        action("Login");
    });

    action("Click on Add new app", function() {
        client.execute(function() {
            var spans = document.getElementsByTagName('span');
            correct_span = null;
            for(var i = 0; i < spans.length; i++) {
                var span = spans[i];
                if (span.innerHTML.trim() === "Add new application") {
                    correct_span = span;
                }
            }
        var buttonId = correct_span.parentElement.parentElement.id;
        document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });
    });

    step("Wait for login to complete", function() {
        client.waitFor('table tr a', TIMEOUT, function(err, res) {

        });
    }, function() {
            action("Click on Add new app");
    });

    action("Fill in and submit initial app information", function() {
        client.setValue(".popupContent .gwt-TextBox", appSettings.name, function(err, res) {

        });
        client.execute(function() {
            var divs = document.getElementsByTagName('div');
            var correct_div = null;
            for (var i = 0; i <divs.length; i++){
                var div = divs[i];
                if (div.innerHTML.trim() === "Upload APK"){
                    correct_div = div;
                }
            }
            var buttonId = correct_div.parentElement.id;
            document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });
    });

    step("Wait for app dialogue", function() {
        client.waitFor(".popupContent fieldset", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Fill in and submit initial app information");
    });

    action("Go to APK upload", function() {
        client.execute(function() {
            var divs = document.getElementsByTagName('div');
            matching_divs = [];

            for (var i = 0; i <divs.length; i++){
                var div = divs[i];
                if (div.innerHTML.trim() === "Upload your first APK to Production"){
                    matching_divs[matching_divs.length] = div;
                }
            }

            var correct_div = null;
            for (var i = 0; i <matching_divs.length ; i++){
                var div = matching_divs[i];
                if (div.parentElement.parentElement.children.length===3){
                    if (div.parentElement.parentElement.tagName === "DIV"){
                        correct_div = div;
                    }
                }
            }

            var buttonId = correct_div.parentElement.id;
            document.querySelector("button#" + buttonId).click();
        }, [], function(err, res) {
            var value = res.value;
        });
    });

    action("Find APK input element", function() {

        client.execute(function(specialId) {
            var interval = window.setInterval(function() {
                var divs = document.getElementsByTagName('div');
                var correct_div = null;
                for (var i = 0; i <divs.length; i++){
                    var div = divs[i];
                    if (div.innerHTML.trim() === "Browse files"){
                        console.log("HIT");
                        correct_div = div;
                    }
                }

                var anyHit = false;
                if (correct_div) {
                    var nodes = correct_div.parentElement.parentElement.children;
                    for (var i =0; i <nodes.length; i++){
                        var node = nodes[i];
                        if (node.tagName==="INPUT"){
                            console.log("hit");
                            node.id= specialId;
                            node.addEventListener("change", function(e) {
                                console.log("NODE CHANGE");
                            });
                            anyHit = true;
                        }
                    }
                }

                if (anyHit) {
                    correct_div.innerHTML = "shit";
                    correct_div.id = "correct_div";
                    window.clearInterval(interval);
                }
            }, 1000);

        }, [specialId], function(err, res) {

        });
    });

    step("Wait for APK page", function() {
        client.waitFor("div[data-stickyscrolling-placeholder]", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Go to APK upload");
        action("Find APK input element");
    });

    var upload_id = 'apk_uploading_id';

    action("Upload APK", function() {
        client.chooseFile("#" + specialId, appSettings.apk_path, function(err, res) {

        });

        client.execute(function(upload_id){
            var p = document.getElementsByTagName('p');
            for (i in p) {
                if (p[i].innerText.trim()==="Supported devices") {
                    p[i].parentElement.id = upload_id;
                    break;
                }
            }

        }, [upload_id]);
    });

    step("Wait for APK box", function() {
        client.waitFor("#correct_div", TIMEOUT, function(err, res) {

        });
    }, function() {
        action("Upload APK");
    });

    action("Go to Store Listing page", function() {
        client.execute(function(){
            var links =  document.getElementsByTagName('a');
            for (i in links){
                var link = links[i];
                if (link.innerText === "Store Listing"){
                    link.click();
                    break;
                }
            }
        });
    });

    step("Wait for APK upload", function() {
        client.waitForVisible('#' + upload_id, TIMEOUT * 10, function(err, res){

        });
    }, function() {
        action("Go to Store Listing page");
    });

    action("Fill in Store Listing information - text and select", function() {

        client.execute(function(){
            var textAreas = document.getElementsByTagName('textArea');
            textAreas[0].id = "textArea0Id";
            textAreas[1].id = "textArea1Id";

            var selectAreas = document.querySelectorAll('select');
            selectAreas[0].id = "selectArea0Id";
            selectAreas[1].id = "selectArea1Id";
            selectAreas[2].id = "selectArea2Id";
        });

        client.setValue("textarea#textArea0Id", appSettings.subtext, function(err, res){

        });

        client.setValue("textarea#textArea1Id", appSettings.promo, function(err,res){

        });

        client.click('#selectArea0Id option[value = ' + appSettings.category + ']');
        client.click('#selectArea1Id option[value = ' + appSettings.subcategory + ']');
        client.click('#selectArea2Id option[value = ' + appSettings.rating + ']');
    });

    action("Fill in Store Listing information - other info", function() {

        function searchForChild(parentTag, attribute, match, nested, childTag, childID, client){
            client.execute(function(parentTag, attribute, match, nested, childTag, childID) {
                var elements = document.querySelectorAll(parentTag);
                var correct_element = null;
                for(var i = 0; i < elements.length; i++) {
                    var element = elements[i];
                    if (element[attribute] === null) {}
                    else if (element[attribute].trim() === match) {
                        correct_element = element;
                    }
                }
                var i = 0;
                while (i < nested){
                    correct_element = correct_element.parentElement;
                    i++;
                }

                var child = correct_element.querySelector(childTag);
                child.id = childID;

            }, [parentTag, attribute, match, nested, childTag, childID]);

            return childID;
        }

        var promo_video_id = searchForChild('p', 'innerText', 'Promo Video', 2, 'input', 'promo_vid_child_id', client);
        var website_id = searchForChild('div', 'innerText', 'Website', 1, 'input', 'website_text_id', client);
        var email_id = searchForChild('div', 'innerText', 'Email', 1, 'input', 'email_text_id', client);
        var phone_id = searchForChild('div', 'innerText', 'Phone', 1, 'input', 'phone_text_id', client);
        var privacy_id = searchForChild('div', 'innerText' ,'Privacy Policy', 1, 'input', 'privacy_policy_id', client);

        client.setValue("#"+promo_video_id, appSettings.promo_vid, function(err, res){});
        client.setValue("#"+website_id, appSettings.website, function(err, res){});
        client.setValue("#"+email_id, appSettings.public_email, function(err, res){});
        client.setValue("#"+phone_id, appSettings.phone, function(err, res){});

        if (appSettings.privacy === null || appSettings.privacy === ""){
            client.execute(function(privacy_id){
                var elem = document.getElementById(privacy_id);
                var checkbox = elem.parentElement.querySelector('input[type="checkbox"]');
                checkbox.click();
            }, [privacy_id]);
        }
        else{
            client.setValue("#"+privacy_id, appSettings.privacy, function(err, res){});
        }
    });

    //not sure how to do this part
    action("Upload screenshots and graphics", function() {

    });

    action("Click save button", function() {
        client.execute(function(){
            var divs = document.querySelectorAll('div');
            correct_div = null;
            for (var i = 0; i <divs.length; i++){
                var div = divs[i];

                if (div.innerHTML.trim() === "Save"){
                    correct_div = div;
                }
            }
            correct_div.parentElement.click()
            correct_div.id = "documentSaved";

        });

        client.waitFor("#documentSaved", TIMEOUT, function(err,res){

        });

        client.execute(function(){
            var spans = document.querySelectorAll('span');

            for (var i in spans){
                var span = spans[i];

                if (span.innerText === "Your application has been saved."){
                    span.id = "documentCompletelySaved";
                }
            }
        });
    });

    step("Wait for Store Listing page", function() {
        client.waitFor('select', TIMEOUT, function(err, res){

            });
    }, function() {
        action("Fill in Store Listing information - text and select");
        action("Fill in Store Listing information - other info");
        action("Upload screenshots and graphics");
        action("Click save button");
    });

    action("Go to Pricing & Distribution page", function() {
        client.execute(function(){
            var links =  document.getElementsByTagName('a');
            for (i in links){
                var link = links[i];
                if (link.innerText === "Pricing & Distribution"){
                    link.click();
                    break;
                }
            }
        });
    });

    step("Wait for completely saved document", function() {
        client.waitFor("#documentCompletelySaved", TIMEOUT, function(err,res) {
        });
    }, function() {
        action("Go to Pricing & Distribution page");
    });

    action("Fill in Pricing & Distribution information - locations", function() {
        client.execute(function(listOfCountries){
            var toReturn = []

            var labels = document.querySelector('h4').parentElement.getElementsByTagName('label');
            for (var i in labels) {
                var label = labels[i];

                if (listOfCountries.indexOf(label.innerText) !== -1 ){
                    var input = label.querySelector('input');
                    if (input.id=== ""){
                        input.id = "languageToClickID" + i;
                    }
                    toReturn[toReturn.length] = input.id;
                }
            }

            for (language in toReturn){
                var elem = document.getElementById(toReturn[language]);
                elem.click();
            }
        }, [appSettings.locations]);
    });

    action("Fill in Pricing & Distribution information - education", function() {

        if (appSettings.education){
            client.execute(function(){
                var field = document.getElementsByTagName('fieldset')[1];
                field.querySelector('input').click();
            });

            client.waitFor('div.popupContent', TIMEOUT, function(err,res){

            });

            client.execute(function(ads, purchases){
                var divs = document.getElementsByTagName('div');
                for (i in divs){
                    var div = divs[i];
                    if (div.innerText === 'Continue'){
                        correct_div.parentElement.click();
                    }
                }

                var popUp = document.querySelector('div.popupContent');

                var inputs = popUp.getElementsByTagName('input');

                if (ads){
                    inputs[0].click();
                }
                else{
                    inputs[1].click();
                }
                if (purchases){
                    inputs[2].click();
                }
                else{
                    inputs[3].click();
                }

                var buttons = popUp.getElementsByTagName('button');
                for (i in buttons){
                    var button = buttons[i];
                    if (button.innerText.trim() === 'Save'){
                        button.click();
                        break;
                    }
                }

            }, [appSettings.education_ads, appSettings.education_purchases]);
        }
    });

    action("Fill in Pricing & Distribution information - opt in", function() {
        client.execute(function(optInValues){
            toReturn = [];
            var field = document.querySelectorAll('fieldset')[2];
            for (i in field.children){
                var child = field.children[i];
                if (child.tagName === "LABEL"){
                    if (optInValues[i]){
                        var input = child.querySelector('input');
                        if (input.id === ""){
                            input.id = "optInButtonToClickID" + child;
                        }
                        toReturn[toReturn.length] = input.id;
                    }
                }
            }

            for (opt in toReturn){
                var elem = document.getElementById(toReturn[opt]);
                elem.click();
            }

        }, [ [appSettings.marketing_opt_out, appSettings.content_guidelines, appSettings.us_export_laws] ]);
    });

    step("Wait for Pricing & Distribution page", function() {
        client.waitFor('colgroup', TIMEOUT, function(err, res){

        });
    }, function() {
        action("Fill in Pricing & Distribution information - locations");
        action("Fill in Pricing & Distribution information - education");
        action("Fill in Pricing & Distribution information - opt in");
        action("Click save button");
    });

    step("Wait for completely saved document", function() {
        client.waitFor("#documentCompletelySaved", TIMEOUT, function(err,res) {

        });
    }, function() {

    });

}

var ScriptRunner = {
    run: function(namespace, action, userOptions) {
        console.log("running " + namespace + ":" + action + " with " + JSON.stringify(userOptions));

        startSelenium(function(client) {

            var selenium = require('selenium-standalone');
            var seleniumServer = selenium({stdio: 'pipe'});

            seleniumServer.stdout.on('data', function(output) {
                var val = output.toString().trim();
                console.log(val);
                if(val.indexOf('jetty.jetty.Server')>-1){
                    client = client.init();
                    start();
                }
            });

            seleniumServer.stderr.on('data', function (data) {
              console.log('stderr: ' + data);
            });

            seleniumServer.on('close', function (code) {
              console.log('child process exited with code ' + code);
            });

            function start() {
                runScript(client, userOptions);
            }

        });
    },
    startSelenium: function(callback) {

        var webdriverjs = require('webdriverjs');
        var driverOptions = {
            desiredCapabilities: {
                browserName: 'chrome'
            }
        };
        var client = webdriverjs.remote(driverOptions);

        callback(client);
    }
};

exports = module.exports = ScriptRunner;
<|endoftext|>


<commit_before>/*!
 * cp-multi-selector
 * author: Bret Little
 * copyright: 2015
 * license: MIT
 * version: 1.1.3
 */
!function(e){function t(n){if(i[n])return i[n].exports;var l=i[n]={exports:{},id:n,loaded:!1};return e[n].call(l.exports,l,l.exports,t),l.loaded=!0,l.exports}var i={};return t.m=e,t.c=i,t.p="",t(0)}([function(e,t,i){"use strict";var n=(i(5),i(2));n.module("cp-multi-selector",[]),i(3)},function(e,t,i){e.exports='
<input type=input class=cp-multi-selector__hidden-input ng-focus=displayDialog()>

{{item.first_name}} {{item.last_name}}

{{item.first_name}} {{item.last_name}}

<input ng-keydown=keyDown($event) class="cps-form-control cp-multi-selector__dialog__input" ng-model=userInput placeholder={{placeholder}}>
<cp-multi-selector-item ng-class="{\'+selected\': isSelected(item), \'+highlighted\': ($index === highlightedIndex) }" ng-click=selectItem(item) ng-repeat="item in filteredItems = (source | filter:userInput | limitTo:4)" template=itemTemplate></cp-multi-selector-item>

'},function(e,t,i){e.exports=angular},function(e,t,i){"use strict";var n=i(4),l=i(1),s=i(6);i(7),angular.module("cp-multi-selector").directive("cpMultiSelector",["$timeout",function(e){return{restrict:"E",scope:{source:"=",selectedItems:"=",template:"=",placeholder:"@",onChange:"&",icon:"@"},template:l,link:function(t,i,l){function o(){var n=i.position(),l=$(window).width();n.left+298>=l&&(t.dialogStyle.right=0),e(function(){t.$apply(function(){var e=i.height();t.dialogStyle.top=e+1+"px"})},100,!1)}function c(){e(function(){t.$apply(function(){t.onChange()})},null,!1)}var r=n.has(l,"single"),p=n.uniqueId();t.dialogStyle={},t.showDialog=!1,t.highlightedIndex=null,t.displayDialog=function(){t.showDialog=!0,setTimeout(function(){i.find(".cp-multi-selector__dialog__input").focus()},100),o()},t.$watch("template",function(e){t.itemTemplate=e||s}),t.$watch("userInput",function(){t.highlightedIndex=null}),t.selectItem=function(e){return r?(t.selectedItems=[e],c(),t.showDialog=!1):(n.find(t.selectedItems,e)?t.removeItem(e):t.selectedItems?t.selectedItems.push(e):t.selectedItems=[e],o(),void c())},t.removeItem=function(e){t.selectedItems=n.without(t.selectedItems,e),c()},t.isSelected=function(e){return!!n.find(t.selectedItems,e)},t.keyDown=function(e){var i=e.which;40===i?n.isNull(t.highlightedIndex)?t.highlightedIndex=0:t.highlightedIndex<t.filteredItems.length-1&&(t.highlightedIndex=t.highlightedIndex+1):38===i?t.highlightedIndex?t.highlightedIndex>0&&(t.highlightedIndex=t.highlightedIndex-1):t.highlightedIndex=0:13===i?n.isNull(t.highlightedIndex)||t.selectItem(t.filteredItems[t.highlightedIndex]):27===i&&(t.showDialog=!1)},$("body").on("click.cpmultiselector"+p,function(e){$(e.target).closest(i).length||t.$apply(function(){t.showDialog=!1})}),t.$on("$destroy",function(){$("body").off("click.cpmultiselector"+p)})}}}]),angular.module("cp-multi-selector").directive("cpMultiSelectorItem",["$compile",function(e){return{restrict:"E",scope:{template:"="},link:function(t,i,n){var l;t.$watch("template",function(n){n&&(l&&l.remove(),l=e(t.template)(t.$parent),i.append(l))})}}}])},function(e,t,i){e.exports=_},function(e,t,i){e.exports=$},function(e,t,i){e.exports='
{{item.first_name[0]}}{{item.last_name[0]}}

{{item.first_name}} {{item.last_name}}

'},function(e,t,i){var n=i(8);"string"==typeof n&&(n=[[e.id,n,""]]);i(9)(n,{})},function(e,t,i){t=e.exports=i(10)(),t.push([e.id,"cp-multi-selector{display:inline-block;position:relative;font-size:1.4rem}.cp-multi-selector{width:340px;z-index:1}.cp-multi-selector__hidden-input{position:absolute}.cp-multi-selector__dialog{background:#fff;padding:16px 16px 8px;position:absolute;top:33px;min-width:298px;width:auto;border-radius:2px}.cp-multi-selector__dialog__items{margin:16px -16px 8px}cp-multi-selector-item{display:block;height:40px;position:relative;padding-top:6px;cursor:pointer;padding-left:16px;padding-right:16px}cp-multi-selector-item:hover,cp-multi-selector-item.\\+highlighted{background-color:#F7F7F7}cp-multi-selector-item.\\+selected .cp-multi-selector-item__icon{background-color:#45A8F8!important}cp-multi-selector-item.\\+selected .cp-multi-selector-item__check{visibility:visible}.cp-multi-selector-item__icon{display:inline-block;vertical-align:middle;height:28px;width:28px;text-align:center;font-weight:600;padding-top:.6rem;border-radius:2px}.cp-multi-selector-item__title{display:inline-block;position:absolute;left:56px;top:12px}.cp-multi-selector-item__check{display:inline-block;visibility:hidden;float:right;font-size:2.6rem;position:relative;right:.2rem}.cp-multi-selector__main-input.cps-form-control{position:relative;z-index:2;padding:2px 2px 0;min-height:32px;height:auto}.cp-multi-selector__pill{display:inline-block;padding:2px 8px;margin-right:5px;height:25px;margin-bottom:3px;vertical-align:top}.cp-multi-selector__pill.\\+inline{position:relative;top:3px}.cp-multi-selector__pill .cps-icon{position:relative;top:-2px;right:-4px;cursor:pointer}.cp-multi-selector__icon{position:relative}",""])},function(e,t,i){function n(e,t){for(var i=0;i<e.length;i++){var n=e[i],l=a[n.id];if(l){l.refs++;for(var s=0;s<l.parts.length;s++)l.parts[s](n.parts[s]);for(;s<n.parts.length;s++)l.parts.push(o(n.parts[s],t))}else{for(var c=[],s=0;s<n.parts.length;s++)c.push(o(n.parts[s],t));a[n.id]={id:n.id,refs:1,parts:c}}}}function l(e){for(var t=[],i={},n=0;n<e.length;n++){var l=e[n],s=l[0],o=l[1],c=l[2],r=l[3],p={css:o,media:c,sourceMap:r};i[s]?i[s].parts.push(p):t.push(i[s]={id:s,parts:[p]})}return t}function s(){var e=document.createElement("style"),t=m();return e.type="text/css",t.appendChild(e),e}function o(e,t){var i,n,l;if(t.singleton){var o=g++;i=h||(h=s()),n=r.bind(null,i,o,!1),l=r.bind(null,i,o,!0)}else i=s(),n=p.bind(null,i),l=function(){i.parentNode.removeChild(i)};return n(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;n(e=t)}else l()}}function c(e,t,i){var n=["/** >>"+t+" **/","/** "+t+"<< **/"],l=e.lastIndexOf(n[0]),s=i?n[0]+i+n[1]:"";if(e.lastIndexOf(n[0])>=0){var o=e.lastIndexOf(n[1])+n[1].length;return e.slice(0,l)+s+e.slice(o)}return e+s}function r(e,t,i,n){var l=i?"":n.css;if(e.styleSheet)e.styleSheet.cssText=c(e.styleSheet.cssText,t,l);else{var s=document.createTextNode(l),o=e.childNodes;o[t]&&e.removeChild(o[t]),o.length?e.insertBefore(s,o[t]):e.appendChild(s)}}function p(e,t){var i=t.css,n=t.media,l=t.sourceMap;if(l&&"function"==typeof btoa)try{i+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(JSON.stringify(l))+" */",i='@import url("data:text/css;base64,'+btoa(i)+'")'}catch(s){}if(n&&e.setAttribute("media",n),e.styleSheet)e.styleSheet.cssText=i;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(i))}}var a={},d=function(e){var t;return function(){return"undefined"==typeof t&&(t=e.apply(this,arguments)),t}},u=d(function(){return/msie 9\b/.test(window.navigator.userAgent.toLowerCase())}),m=d(function(){return document.head||document.getElementsByTagName("head")[0]}),h=null,g=0;e.exports=function(e,t){t=t||{},"undefined"==typeof t.singleton&&(t.singleton=u());var i=l(e);return n(i,t),function(e){for(var s=[],o=0;o<i.length;o++){var c=i[o],r=a[c.id];r.refs--,s.push(r)}if(e){var p=l(e);n(p,t)}for(var o=0;o<s.length;o++){var r=s[o];if(0===r.refs){for(var d=0;d<r.parts.length;d++)r.parts[d]();delete a[r.id]}}}}},function(e,t,i){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t<this.length;t++){var i=this[t];e.push(i[2]?"@media "+i[2]+"{"+i[1]+"}":i[1])}return e.join("")},e}}]);<commit_msg>Update built file<commit_after>/*!
 * cp-multi-selector
 * author: Bret Little
 * copyright: 2015
 * license: MIT
 * version: 1.1.3
 */
!function(e){function t(n){if(i[n])return i[n].exports;var l=i[n]={exports:{},id:n,loaded:!1};return e[n].call(l.exports,l,l.exports,t),l.loaded=!0,l.exports}var i={};return t.m=e,t.c=i,t.p="",t(0)}([function(e,t,i){"use strict";var n=(i(1),i(2));n.module("cp-multi-selector",[]),i(3)},function(e,t,i){e.exports=$},function(e,t,i){e.exports=angular},function(e,t,i){"use strict";var n=i(4),l=i(5),s=i(6);i(7),angular.module("cp-multi-selector").directive("cpMultiSelector",["$timeout",function(e){return{restrict:"E",scope:{source:"=",selectedItems:"=",template:"=",placeholder:"@",onChange:"&",icon:"@"},template:l,link:function(t,i,l){function o(){var n=i.position(),l=$(window).width();n.left+298>=l&&(t.dialogStyle.right=0),e(function(){t.$apply(function(){var e=i.height();t.dialogStyle.top=e+1+"px"})},100,!1)}function c(){e(function(){t.$apply(function(){t.onChange()})},null,!1)}var r=n.has(l,"single"),p=n.uniqueId();t.dialogStyle={},t.showDialog=!1,t.highlightedIndex=null,t.displayDialog=function(){t.showDialog=!0,setTimeout(function(){i.find(".cp-multi-selector__dialog__input").focus()},100),o()},t.$watch("template",function(e){t.itemTemplate=e||s}),t.$watch("userInput",function(){t.highlightedIndex=null}),t.selectItem=function(e){return r?(t.selectedItems=[e],c(),t.showDialog=!1):(n.find(t.selectedItems,e)?t.removeItem(e):t.selectedItems?t.selectedItems.push(e):t.selectedItems=[e],o(),void c())},t.removeItem=function(e){t.selectedItems=n.without(t.selectedItems,e),c()},t.isSelected=function(e){return!!n.find(t.selectedItems,e)},t.keyDown=function(e){var i=e.which;40===i?n.isNull(t.highlightedIndex)?t.highlightedIndex=0:t.highlightedIndex<t.filteredItems.length-1&&(t.highlightedIndex=t.highlightedIndex+1):38===i?t.highlightedIndex?t.highlightedIndex>0&&(t.highlightedIndex=t.highlightedIndex-1):t.highlightedIndex=0:13===i?n.isNull(t.highlightedIndex)||t.selectItem(t.filteredItems[t.highlightedIndex]):27===i&&(t.showDialog=!1)},$("body").on("click.cpmultiselector"+p,function(e){$(e.target).closest(i).length||t.$apply(function(){t.showDialog=!1})}),t.$on("$destroy",function(){$("body").off("click.cpmultiselector"+p)})}}}]),angular.module("cp-multi-selector").directive("cpMultiSelectorItem",["$compile",function(e){return{restrict:"E",scope:{template:"="},link:function(t,i,n){var l;t.$watch("template",function(n){n&&(l&&l.remove(),l=e(t.template)(t.$parent),i.append(l))})}}}])},function(e,t,i){e.exports=_},function(e,t,i){e.exports='
<input type=input class=cp-multi-selector__hidden-input ng-focus=displayDialog()>

{{item.first_name}} {{item.last_name}}

{{item.first_name}} {{item.last_name}}

<input ng-keydown=keyDown($event) class="cps-form-control cp-multi-selector__dialog__input" ng-model=userInput placeholder={{placeholder}}>
<cp-multi-selector-item ng-class="{\'+selected\': isSelected(item), \'+highlighted\': ($index === highlightedIndex) }" ng-click=selectItem(item) ng-repeat="item in filteredItems = (source | filter:userInput | limitTo:4)" template=itemTemplate></cp-multi-selector-item>

'},function(e,t,i){e.exports='
{{item.first_name[0]}}{{item.last_name[0]}}

{{item.first_name}} {{item.last_name}}

'},function(e,t,i){var n=i(8);"string"==typeof n&&(n=[[e.id,n,""]]);i(10)(n,{})},function(e,t,i){t=e.exports=i(9)(),t.push([e.id,"cp-multi-selector{display:inline-block;position:relative;font-size:1.4rem}.cp-multi-selector{width:340px;z-index:1}.cp-multi-selector__hidden-input{position:absolute}.cp-multi-selector__dialog{background:#fff;padding:16px 16px 8px;position:absolute;top:33px;min-width:298px;width:auto;border-radius:2px}.cp-multi-selector__dialog__items{margin:16px -16px 8px}cp-multi-selector-item{display:block;height:40px;position:relative;padding-top:6px;cursor:pointer;padding-left:16px;padding-right:16px}cp-multi-selector-item:hover,cp-multi-selector-item.\\+highlighted{background-color:#F7F7F7}cp-multi-selector-item.\\+selected .cp-multi-selector-item__icon{background-color:#45A8F8!important}cp-multi-selector-item.\\+selected .cp-multi-selector-item__check{visibility:visible}.cp-multi-selector-item__icon{display:inline-block;vertical-align:middle;height:28px;width:28px;text-align:center;font-weight:600;padding-top:.6rem;border-radius:2px}.cp-multi-selector-item__title{display:inline-block;position:absolute;left:56px;top:12px}.cp-multi-selector-item__check{display:inline-block;visibility:hidden;float:right;font-size:2.6rem;position:relative;right:.2rem}.cp-multi-selector__main-input.cps-form-control{position:relative;z-index:2;padding:2px 2px 0;min-height:32px;height:auto}.cp-multi-selector__pill{display:inline-block;padding:2px 8px;margin-right:5px;height:25px;margin-bottom:3px;vertical-align:top}.cp-multi-selector__pill.\\+inline{position:relative;top:3px}.cp-multi-selector__pill .cps-icon{position:relative;top:-2px;right:-4px;cursor:pointer}.cp-multi-selector__icon{position:relative}",""])},function(e,t,i){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t<this.length;t++){var i=this[t];i[2]?e.push("@media "+i[2]+"{"+i[1]+"}"):e.push(i[1])}return e.join("")},e}},function(e,t,i){function n(e,t){for(var i=0;i<e.length;i++){var n=e[i],l=a[n.id];if(l){l.refs++;for(var s=0;s<l.parts.length;s++)l.parts[s](n.parts[s]);for(;s<n.parts.length;s++)l.parts.push(o(n.parts[s],t))}else{for(var c=[],s=0;s<n.parts.length;s++)c.push(o(n.parts[s],t));a[n.id]={id:n.id,refs:1,parts:c}}}}function l(e){for(var t=[],i={},n=0;n<e.length;n++){var l=e[n],s=l[0],o=l[1],c=l[2],r=l[3],p={css:o,media:c,sourceMap:r};i[s]?i[s].parts.push(p):t.push(i[s]={id:s,parts:[p]})}return t}function s(){var e=document.createElement("style"),t=m();return e.type="text/css",t.appendChild(e),e}function o(e,t){var i,n,l;if(t.singleton){var o=g++;i=h||(h=s()),n=r.bind(null,i,o,!1),l=r.bind(null,i,o,!0)}else i=s(),n=p.bind(null,i),l=function(){i.parentNode.removeChild(i)};return n(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;n(e=t)}else l()}}function c(e,t,i){var n=["/** >>"+t+" **/","/** "+t+"<< **/"],l=e.lastIndexOf(n[0]),s=i?n[0]+i+n[1]:"";if(e.lastIndexOf(n[0])>=0){var o=e.lastIndexOf(n[1])+n[1].length;return e.slice(0,l)+s+e.slice(o)}return e+s}function r(e,t,i,n){var l=i?"":n.css;if(e.styleSheet)e.styleSheet.cssText=c(e.styleSheet.cssText,t,l);else{var s=document.createTextNode(l),o=e.childNodes;o[t]&&e.removeChild(o[t]),o.length?e.insertBefore(s,o[t]):e.appendChild(s)}}function p(e,t){var i=t.css,n=t.media,l=t.sourceMap;if(l&&"function"==typeof btoa)try{i+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(JSON.stringify(l))+" */",i='@import url("data:text/css;base64,'+btoa(i)+'")'}catch(s){}if(n&&e.setAttribute("media",n),e.styleSheet)e.styleSheet.cssText=i;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(i))}}var a={},d=function(e){var t;return function(){return"undefined"==typeof t&&(t=e.apply(this,arguments)),t}},u=d(function(){return/msie 9\b/.test(window.navigator.userAgent.toLowerCase())}),m=d(function(){return document.head||document.getElementsByTagName("head")[0]}),h=null,g=0;e.exports=function(e,t){t=t||{},"undefined"==typeof t.singleton&&(t.singleton=u());var i=l(e);return n(i,t),function(e){for(var s=[],o=0;o<i.length;o++){var c=i[o],r=a[c.id];r.refs--,s.push(r)}if(e){var p=l(e);n(p,t)}for(var o=0;o<s.length;o++){var r=s[o];if(0===r.refs){for(var d=0;d<r.parts.length;d++)r.parts[d]();delete a[r.id]}}}}}]);<|endoftext|>


<commit_before>function echo ( ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: echo is bad
    // +   improved by: Nate
    // +    revised by: Der Simon (http://innerdom.sourceforge.net/)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Eugene Bulkin (http://doubleaw.com/)
    // %        note 1: The function still has issues with outputting certain kinds of XML, such as
    // %        note 1: attributes defined with apostrophes, or creating namespaced XML, etc.
    // %        note 1: We might at some point solve this by building on http://code.google.com/p/jssaxparser
    // %        note 1: and using that, though it would be even larger; if browsers start to support
    // %        note 1: DOM Level 3 Load and Save (parsing/serializing), we wouldn't need any
    // %        note 1: such long code (even most of the code below).
    // %        note 2: InnerHTML() is better because it works (and it's fast),
    // %        note 2: but using innerHTML on the BODY is very dangerous because
    // %        note 2: you will break all references to HTMLElements that were done before
    // *     example 1: echo('Hello', 'World');
    // *     returns 1: undefined

    var arg = '', argc = arguments.length, argv = arguments, i = 0;
	var d = this.window.document;

    var stringToDOM = function (q){
        var s = function(a){
            return a.replace(/&/g,'&').replace(/>/g,'>').replace(/</g,'<').replace(/ /g,' ').replace(/"/g,'"');
        };
        var t = function(a){
            return a.replace(/ /g,'');
        };
        var u = function(a){
            var b,c,e,f,g,h,i;
            b=d.createDocumentFragment();
            c=a.indexOf(' ');
            if (c === -1) {
                b.appendChild(d.createElement(a.toLowerCase()));
            } else {
                i = t(a.substring(0,c)).toLowerCase();
                a = a.substr(c+1);
                b.appendChild(d.createElement(i));
                while(a.length){
                    e=a.indexOf('=');
                    if(e>=0){
                        f=t(a.substring(0,e)).toLowerCase();
                        g=a.indexOf('"');
                        a=a.substr(g+1);
                        g=a.indexOf('"');
                        h=s(a.substring(0,g));
                        a=a.substr(g+2);
                        b.lastChild.setAttribute(f,h);
                    }else{
                        break;
                    }
                }
            }
            return b;
        };
        var v = function(a,b,c){
            var e,f;
            e=b;
            c=c.toLowerCase();
            f=e.indexOf('</'+c+'>');
            a=a.concat(e.substring(0,f));
            e=e.substr(f);
            while(a.indexOf('<'+c)!=-1){
                a=a.substr(a.indexOf('<'+c));
                a=a.substr(a.indexOf('>')+1);
                e=e.substr(e.indexOf('>')+1);
                f=e.indexOf('</'+c+'>');
                a=a.concat(e.substring(0,f));
                e=e.substr(f);
            }
            return b.length-e.length;
        };
        var w = function(a){
            var b,c,e,f,g,h,i,j,k,l,m,n,o,p,q;
            b=d.createDocumentFragment();
            while(a&&a.length){
                c=a.indexOf('<');
                if(c===-1){
                    a=s(a);
                    b.appendChild(d.createTextNode(a));
                    a=null;
                } else if(c){
                    q=s(a.substring(0,c));
                    b.appendChild(d.createTextNode(q));
                    a=a.substr(c);
                } else{
                    e=a.indexOf('<!--');
                    if(!e){
                        f=a.indexOf('-->');
                        g=a.substring(4,f);
                        g=s(g);
                        b.appendChild(d.createComment(g));
                        a=a.substr(f+3);
                    } else{
                        h=a.indexOf('>');
                        if(a.substring(h-1,h)==='/'){
                            i=a.indexOf('/>');
                            j=a.substring(1,i);
                            b.appendChild(u(j));
                            a=a.substr(i+2);
                        } else{
                            k=a.indexOf('>');
                            l=a.substring(1,k);
                            m=d.createDocumentFragment();
                            m.appendChild(u(l));
                            a=a.substr(k+1);
                            n=a.substring(0,a.indexOf('</'));
                            a=a.substr(a.indexOf('</'));
                            if(n.indexOf('<')!=-1){
                                o=m.lastChild.nodeName;
                                p=v(n,a,o);
                                n=n.concat(a.substring(0,p));
                                a=a.substr(p);
                            }
                            a=a.substr(a.indexOf('>')+1);
                            m.lastChild.appendChild(w(n));
                            b.appendChild(m);
                        }
                    }
                }
            }
            return b;
        };
        return w(q);
    };

    for (i = 0; i < argc; i++ ) {
        arg = argv[i];
        if (d.createDocumentFragment && d.createTextNode && d.appendChild) {
            if (d.body) {
                d.body.appendChild(stringToDOM(arg));
            } else {
                d.documentElement.appendChild(stringToDOM(arg));
            }
        } else if (d.write) {
            d.write(arg);
        } else {
            print(arg);
        }
    }
}<commit_msg>Add new version of echo which potentially supports single quoted attributes, namespaces, etc., and also shortens function size<commit_after>function echo ( ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: echo is bad
    // +   improved by: Nate
    // +    revised by: Der Simon (http://innerdom.sourceforge.net/)
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Eugene Bulkin (http://doubleaw.com/)
    // +   input by: JB
    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: If browsers start to support DOM Level 3 Load and Save (parsing/serializing),
    // %        note 1: we wouldn't need any such long code (even most of the code below). See
    // %        note 1: link below for a cross-browser implementation in JavaScript. HTML5 might
    // %        note 1: possibly support DOMParser, but that is not presently a standard.
    // %        note 2: Although innerHTML is widely used and may become standard as of HTML5, it is also not ideal for
    // %        note 2: use with a temporary holder before appending to the DOM (as is our last resort below),
    // %        note 2: since it may not work in an XML context
    // %        note 3: Using innerHTML to directly add to the BODY is very dangerous because it will
    // %        note 3: break all pre-existing references to HTMLElements.
    // *     example 1: echo('Hello', 'World');
    // *     returns 1: undefined

    var arg = '', argc = arguments.length, argv = arguments, i = 0;
	var d = this.window.document;

    var stringToDOM = function (q) {
        if (window.DOMImplementationLS &&
            window.DOMImplementationLS.createLSInput &&
            window.DOMImplementationLS.createLSParser) { // Follows the DOM 3 Load and Save standard, but not
            // implemented in browsers at present; HTML5 is to standardize on innerHTML, but not for XML (though
            // possibly will also standardize with DOMParser); in the meantime, to ensure fullest browser support, could
            // attach http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.js (see http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.xhtml for a simple test file)
            var lsInput = DOMImplementationLS.createLSInput();
            lsInput.stringData = q;
            var lsParser = DOMImplementationLS.createLSParser(1, null); // synchronous, no schema type
            return lsParser.parse(lsInput);
        }
        else if (window.DOMParser) {
            return new DOMParser().parseFromString(q, 'text/xml').documentElement;
        }
        else if (window.ActiveXObject) {
            var d = new ActiveXObject('MSXML2.DOMDocument');
             d.loadXML(q);
             return d;
        }
        /*else if (window.XMLHttpRequest) { // Supposed to work in older Safari
            var req = new window.XMLHttpRequest;
            req.open('GET', 'data:application/xml;charset=utf-8,'+encodeURIComponent(q), false);
            if (req.overrideMimeType) {
                req.overrideMimeType('application/xml');
            }
            req.send(null);
            return req.responseXML;
        }*/
        else if (document.createDocumentFragment) { // Document fragment did not work with innerHTML, so we create a temporary element holder
            var holder;
            if (document.createElementNS) {
                holder = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
            }
            else {
                holder = document.createElement('div'); // Document fragment did not work with innerHTML
            }
            holder.innerHTML = q;
            var df = document.createDocumentFragment();
            while (holder.firstChild) {
                df.appendChild(holder.firstChild);
            }
            return df;
        }
        throw 'Your browser does not support DOM parsing as required by echo()';
    };

    for (i = 0; i < argc; i++ ) {
        arg = argv[i];
        if (d.createDocumentFragment && d.createTextNode && d.appendChild) {
            if (d.body) {
                d.body.appendChild(stringToDOM(arg));
            } else {
                d.documentElement.appendChild(stringToDOM(arg));
            }
        } else if (d.write) {
            d.write(arg);
        }/* else { // This could recurse if we ever add print!
            print(arg);
        }*/
    }
}<|endoftext|>


<commit_before>block('page').elem('content').match(function () {
  return this.mods.layout !== 'root'
})(
  content()(function () {
    return [
      {
        block: 'row',
        content: [
          {
            elem: 'col',
            elemMods: { sw: 24, lw: 5 },
            content: { block: 'side-nav' }
          },
          {
            elem: 'col',
            elemMods: { sw: 24, lw: 18, lo: 1 },
            content: [
              { block: 'page', elem: 'edit' }
            ].concat(applyNext())
          },

        ]
      }
    ]
  })
)

block('page').elem('content').mod('layout', 'root')(
  content()(function() {
    var md = applyNext()
    var lastRowIndex = -1
    var even, data, tabs
    var content = []

    md.forEach(function (node) {
      if (node && node.tag === 'h2') {
        lastRowIndex++
        even = !!(lastRowIndex % 2)
        data = [node]
        tabs = []

        content.push({
          block: 'row',
          content: [
            {
              elem: 'col',
              elemMods: { sw: 24, lw: 11, lo: even && 2 },
              content: data
            }, {
              elem: 'col',
              elemMods: { sw: 24, lw: 11, lo: even || 2, lof: even, xlof: even, xxlof: even },
              content: tabs
            }
          ]
        })
      } else if (node && node.block === 'tabs') {
        tabs.push(node)
      } else {
        data.push(node)
      }
    })
    return content
  })
)
<commit_msg>feat: ignore content before headers on root<commit_after>block('page').elem('content').match(function () {
  return this.mods.layout !== 'root'
})(
  content()(function () {
    return [
      {
        block: 'row',
        content: [
          {
            elem: 'col',
            elemMods: { sw: 24, lw: 5 },
            content: { block: 'side-nav' }
          },
          {
            elem: 'col',
            elemMods: { sw: 24, lw: 18, lo: 1 },
            content: [
              { block: 'page', elem: 'edit' }
            ].concat(applyNext())
          },

        ]
      }
    ]
  })
)

block('page').elem('content').mod('layout', 'root')(
  content()(function() {
    var md = applyNext()
    var lastRowIndex = -1
    var even, data, tabs
    var content = []

    md.forEach(function (node) {
      if (node && node.tag === 'h2') {
        lastRowIndex++
        even = !!(lastRowIndex % 2)
        data = [node]
        tabs = []

        content.push({
          block: 'row',
          content: [
            {
              elem: 'col',
              elemMods: { sw: 24, lw: 11, lo: even && 2 },
              content: data
            }, {
              elem: 'col',
              elemMods: { sw: 24, lw: 11, lo: even || 2, lof: even, xlof: even, xxlof: even },
              content: tabs
            }
          ]
        })
      } else if (node && node.block === 'tabs') {
        tabs && tabs.push(node)
      } else {
        data && data.push(node)
      }
    })
    return content
  })
)
<|endoftext|>