<commit_before>/*
 * Gruntfile.js
 */

'use strict';

var path = require('path'),
    util = require('util');

var _ = require('lodash'),
    coffeeify = require('coffeeify'),
    hbsfy = require('hbsfy'),
    ngmin = require('ngmin'),
    rfileify = require('rfileify'),
    uglify = require('uglify-js'),
    wrench = require('wrench');

var project = require('./project');

module.exports = function (grunt) {
  // load all grunt tasks
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  grunt.loadNpmTasks('intern');

  // Project configuration.
  grunt.initConfig({
    project: project,
    browserify2: {  // grunt-browserify2
      dev: {
        entry: './<%= project.path.client %>/js/index.js',
        compile: '<%= project.path.temp %>/js/main.js',
        debug: true,
        beforeHook: function (bundle) {
          bundle.transform(coffeeify);
          bundle.transform(hbsfy);
          bundle.transform(rfileify);
        }
      },
      dist: {
        entry: './<%= project.path.client %>/js/index.js',
        compile: '<%= project.path.dist %>/js/main.js',
        beforeHook: function (bundle) {
          bundle.transform(coffeeify);
          bundle.transform(hbsfy);
          bundle.transform(rfileify);
        },
        afterHook: function (source) {
          source = ngmin.annotate(source);
          source = uglify.minify(source, { fromString: true }).code;
          return source;
        }
      }
    },
    cachebust: {
      dev: {
        files: {
          src: [
            '<%= project.path.temp %>/*.html'
          ]
        }
      },
      dist: {
        files: {
          src: [
            '<%= project.path.dist %>/*.html',
            '<%= project.path.server %>/views/_layouts/**/*.hbs'
          ]
        }
      }
    },
    clean: {  // grunt-contrib-clean
      dev: [
        '<%= project.path.temp %>'
      ],
      dist: [
        '<%= project.path.dist %>'
      ]
    },
    copy: {  // grunt-contrib-copy
      dev: {
        files: [
          {
            expand: true,
            flatten: true,
            cwd: '<%= project.path.bower %>',
            dest: '<%= project.path.temp %>/js/vendor',
            src: [
              'es5-shim/es5-shim.js',
              'json3/lib/json3.js',
              'modernizr/modernizr.js'
            ]
          },
          {
            expand: true,
            cwd: '<%= project.path.client %>',
            dest: '<%= project.path.temp %>',
            src: [
              '*.html'
            ]
          }
        ]
      },
      dist: {
        files: [
          {
            expand: true,
            flatten: true,
            cwd: '<%= project.path.bower %>',
            dest: '<%= project.path.dist %>/js/vendor',
            src: [
              'es5-shim/es5-shim.js',
              'json3/lib/json3.js',
              'modernizr/modernizr.js'
            ]
          },
          {
            expand: true,
            cwd: '<%= project.path.client %>',
            dest: '<%= project.path.dist %>',
            src: [
              '../<%= project.path.bower %>/**/*',
              'fonts/**/*'
            ]
          },
          {
            expand: true,
            cwd: '<%= project.path.client %>',
            dest: '<%= project.path.dist %>',
            src: [
              '*.html'
            ]
          }
        ]
      }
    },
    express: {  // grunt-express
      server: {
        options: {
          debug: true,
          livereload: project.server.livereload,
          port: '<%= process.env.PORT || project.server.port %>',
          server: path.resolve('<%= project.path.server %>')
        }
      }
    },
    htmlmin: {  // grunt-contrib-htmlmin
      dist: {
        files: [{
          expand: true,
          cwd: '<%= project.path.dist %>',
          src: [
            '*.html'
          ],
          dest: '<%= project.path.dist %>'
        }]
      }
    },
    imagemin: {  // grunt-contrib-imagemin
      dist: {
        files: [{
          expand: true,
          cwd: '<%= project.path.client %>/img',
          dest: '<%= project.path.dist %>/img',
          src: '**/*.{gif,jpg,png}'
        }]
      }
    },
    intern: {  // intern
      client: {
        options: {
          config: 'test/intern'
        }
      },
      clientSuiteGet: {
        options: {
          config: 'test/intern',
          suites: ['test/lib/get']
        }
      },
      runner: {
        options: {
          config: 'test/intern',
          runType: 'runner'
        }
      }
    },
    jshint: {  // grunt-contrib-jshint
      options: {
        jshintrc: '.jshintrc'
      },
      client: [
        '<%= project.path.client %>/js/**/*.js',
        '!<%= project.path.client %>/js/node_modules/**/*.js',
        '<%= project.path.client %>/js/node_modules/*.js',
        '<%= project.path.client %>/node_modules/*.js',
      ],
      server: [
        '<%= project.path.server %>/**/*.js'
      ],
      grunt: [
        'Gruntfile.js'
      ]
    },
    karma: {  // grunt-karma
      single: {
        configFile: '<%= project.path.config %>/test/karma-unit.conf.js',
        singleRun: true
      },
      multi: {
        configFile: '<%= project.path.config %>/test/karma-unit.conf.js',
        singleRun: false
      },
      e2e: {
        configFile: '<%= project.path.config %>/test/karma-e2e.conf.js',
        singleRun: true
      }
    },
    less: {  // grunt-contrib-less
      dev: {
        options: {
          dumpLineNumbers: 'comments',
          paths: ['<%= project.path.client %>/less']
        },
        files: {
          '<%= project.path.temp %>/css/main.css': '<%= project.path.client %>/less/index.less',
          '<%= project.path.temp %>/css/static.css': '<%= project.path.client %>/less/_layouts/static/index.less'
        }
      },
      dist: {
        options: {
          paths: ['<%= project.path.client %>/less'],
          compress: true,
          yuicompress: true
        },
        files: {
          '<%= project.path.dist %>/css/main.css': '<%= project.path.client %>/less/index.less',
          '<%= project.path.dist %>/css/static.css': '<%= project.path.client %>/less/_layouts/static/index.less'
        }
      }
    },
    open: {  // grunt-open
      dev: {
        url: 'http://localhost:<%= process.env.PORT || project.server.port %>'
      }
    },
    protractor: {  // grunt-protractor-runner
      options: {
        keepAlive: true,
        noColor: false
      },
      e2e: {
        configFile: '<%= project.path.config %>/test/protractor-e2e.conf.js',
      }
    },
    uglify: {  // grunt-contrib-uglify
      dist: {
        options: {
          beautify: true
        },
        files: _.transform({
          paths: _.map([
            'es5-shim.js',
            'json3.js',
            'modernizr.js'
          ], function (path) {
            return project.path.dist + '/js/vendor/' + path;
          })
        }, function (result, files) {
          _.assign(result, _.object(files, files));
        })
      }
    },
    usemin: {  // grunt-usemin
      options: {
        dirs: ['<%= project.path.dist %>']
      },
      html: ['<%= project.path.dist %>/*.html'],
      css: ['<%= project.path.dist %>/css/{,*/}*.css']
    },
    useminPrepare: {  // grunt-usemin
      options: {
        dest: '<%= project.path.dist %>'
      },
      html: '<%= project.path.client %>/*.html'
    },
    watch: {  // grunt-contrib-watch
      livereload: {
        options: {
          livereload: project.server.livereload
        },
        files: [
          '<%= project.path.client %>/fonts/{,*/}*',
          '<%= project.path.client %>/img/**/*.{gif,jpg,png}',
          '<%= project.path.server %>/views/**/*.hbs',
          '<%= project.path.static %>/**/*',
          '<%= project.path.temp %>/*.html',
          '<%= project.path.temp %>/css/{,*/}*.css',
          '<%= project.path.temp %>/js/{,*/}*.js'
        ]
      },
      html: {
        files: [
          '<%= project.path.client %>/*.html'
        ],
        tasks: [
          'copy:dev',
          'cachebust:dev'
        ]
      },
      less: {
        files: ['<%= project.path.client %>/less/**/*.less'],
        tasks: ['less:dev']
      },
      js: {
        files: [
          '<%= jshint.client %>',
          '<%= project.path.client %>/js/**/*.html',
          '!<%= project.path.client %>/js/bower_components/**/*.html'
        ],
        tasks: ['browserify2:dev']
      }
    }
  });

  grunt.registerTask('buildDev', [
    'clean:dev',
    'browserify2:dev',
    'less:dev',
    'copy:dev',
    'symlinkDev',
    'cachebust:dev'
  ]);

  grunt.registerTask('buildDist', [
    'jshint',
    'clean:dist',
    'browserify2:dist',
    'less:dist',
    'useminPrepare',
    'htmlmin:dist',
    'imagemin:dist',
    'copy:dist',
    'symlinkDist',
    'cachebust:dist',
    'usemin',
    'uglify:dist'
  ]);

  grunt.registerMultiTask('cachebust', function () {
    this.files.forEach(function (file) {
      file.src.filter(function (filepath) {
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function (filepath) {
        var hash = '' + new Date().getTime(),
            data = grunt.file.read(filepath, { encoding: 'utf-8' });
        grunt.util._.each({
          js: {
            src: /<script.+src=['"](?!http:|https:|\/\/)([^"']+)["']/gm,
            file: /src=['"]([^"']+)["']/m
          },
          css: {
            src: /<link.+href=["'](?!http:|https:|\/\/).*\.css("|\?.*")/gm,
            file: /href=['"]([^"']+)["']/m
          },
          images: {
            src: /<img[^\>]+src=['"](?!http:|https:|\/\/|data:image)([^"']+)["']/gm,
            file: /src=['"]([^"']+)["']/m
          }
        }, function (regex) {
          if (/\.hbs$/.test(filepath)) { return; }
          var matches = data.match(regex.src) || [];
          if (matches.length) {
            console.log(matches);
          }
          matches.forEach(function (snippet) {
            snippet = snippet.substring(0, snippet.length - 1);
            data = data.replace(snippet, snippet.split('?')[0] + '?' + hash);
          });
        });
        if (!/\.hbs$/.test(filepath)) {
          grunt.file.write(filepath, data);
          grunt.log.writeln('"' + filepath + '" busted.');
        }
        // Save hash to file so express server can use the value.
        var cachebustData = {};
        try {
          cachebustData = grunt.file.readJSON('.cachebust');
        } catch (e) {}
        cachebustData[filepath] = hash;
        grunt.file.write('.cachebust', JSON.stringify(cachebustData, null, 2));
        grunt.log.writeln('".cachebust" updated.');
      });
    });
  });

  grunt.registerTask('symlinkDev', function () {
    ['fonts'].forEach(function (dir) {
      var symlinks = require(util.format('./%s/%s/.symlinks', project.path.client, dir));
      _.each(symlinks, function (source, target) {
        source = path.resolve(path.join(project.path.client, dir, source));
        target = path.resolve(path.join(project.path.temp, dir, target));
        wrench.mkdirSyncRecursive(path.join(project.path.temp, dir));
        wrench.copyDirSyncRecursive(source, target);
      });
      console.info('Resolved symlinks: %s', path.resolve(project.path.client, dir));
    });
  });

  grunt.registerTask('symlinkDist', function () {
    ['fonts'].forEach(function (dir) {
      var symlinks = require(util.format('./%s/%s/.symlinks', project.path.client, dir));
      _.each(symlinks, function (source, target) {
        source = path.resolve(path.join(project.path.client, dir, source));
        target = path.resolve(path.join(project.path.dist, dir, target));
        wrench.mkdirSyncRecursive(path.join(project.path.dist, dir));
        wrench.copyDirSyncRecursive(source, target);
      });
      console.info('Resolved symlinks: %s', path.resolve(project.path.dist, dir));
    });
  });

  grunt.registerTask('serverDev', function () {
    grunt.task.run([
      'express',
      'open'
    ]);
    if (process.env.NODE_ENV !== 'heroku' && process.env.NODE_ENV !== 'production') {
      grunt.task.run('watch');
    }
  });

  grunt.registerTask('build', 'buildDist');
  grunt.registerTask('test', [
    'jshint',
    'protractor'
    // 'karma:multi'
  ]);

  // Shortcuts
  grunt.registerTask('b', 'build');
  grunt.registerTask('c', 'clean');
  grunt.registerTask('d', 'buildDev');
  grunt.registerTask('s', 'serverDev');
  grunt.registerTask('t', 'test');

  // Default
  grunt.registerTask('default', ['buildDev', 'serverDev']);
};
<commit_msg>Beautify on while develop client-dist<commit_after>/*
 * Gruntfile.js
 */

'use strict';

var path = require('path'),
    util = require('util');

var _ = require('lodash'),
    coffeeify = require('coffeeify'),
    hbsfy = require('hbsfy'),
    ngmin = require('ngmin'),
    rfileify = require('rfileify'),
    uglify = require('uglify-js'),
    wrench = require('wrench');

var project = require('./project');

module.exports = function (grunt) {
  // load all grunt tasks
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  grunt.loadNpmTasks('intern');

  // Project configuration.
  grunt.initConfig({
    project: project,
    browserify2: {  // grunt-browserify2
      dev: {
        entry: './<%= project.path.client %>/js/index.js',
        compile: '<%= project.path.temp %>/js/main.js',
        debug: true,
        beforeHook: function (bundle) {
          bundle.transform(coffeeify);
          bundle.transform(hbsfy);
          bundle.transform(rfileify);
        }
      },
      dist: {
        entry: './<%= project.path.client %>/js/index.js',
        compile: '<%= project.path.dist %>/js/main.js',
        beforeHook: function (bundle) {
          bundle.transform(coffeeify);
          bundle.transform(hbsfy);
          bundle.transform(rfileify);
        },
        afterHook: function (source) {
          source = ngmin.annotate(source);
          source = uglify.minify(source, { fromString: true }).code;
          return source;
        }
      }
    },
    cachebust: {
      dev: {
        files: {
          src: [
            '<%= project.path.temp %>/*.html'
          ]
        }
      },
      dist: {
        files: {
          src: [
            '<%= project.path.dist %>/*.html',
            '<%= project.path.server %>/views/_layouts/**/*.hbs'
          ]
        }
      }
    },
    clean: {  // grunt-contrib-clean
      dev: [
        '<%= project.path.temp %>'
      ],
      dist: [
        '<%= project.path.dist %>'
      ]
    },
    copy: {  // grunt-contrib-copy
      dev: {
        files: [
          {
            expand: true,
            flatten: true,
            cwd: '<%= project.path.bower %>',
            dest: '<%= project.path.temp %>/js/vendor',
            src: [
              'es5-shim/es5-shim.js',
              'json3/lib/json3.js',
              'modernizr/modernizr.js'
            ]
          },
          {
            expand: true,
            cwd: '<%= project.path.client %>',
            dest: '<%= project.path.temp %>',
            src: [
              '*.html'
            ]
          }
        ]
      },
      dist: {
        files: [
          {
            expand: true,
            flatten: true,
            cwd: '<%= project.path.bower %>',
            dest: '<%= project.path.dist %>/js/vendor',
            src: [
              'es5-shim/es5-shim.js',
              'json3/lib/json3.js',
              'modernizr/modernizr.js'
            ]
          },
          {
            expand: true,
            cwd: '<%= project.path.client %>',
            dest: '<%= project.path.dist %>',
            src: [
              '../<%= project.path.bower %>/**/*',
              'fonts/**/*'
            ]
          },
          {
            expand: true,
            cwd: '<%= project.path.client %>',
            dest: '<%= project.path.dist %>',
            src: [
              '*.html'
            ]
          }
        ]
      }
    },
    express: {  // grunt-express
      server: {
        options: {
          debug: true,
          livereload: project.server.livereload,
          port: '<%= process.env.PORT || project.server.port %>',
          server: path.resolve('<%= project.path.server %>')
        }
      }
    },
    htmlmin: {  // grunt-contrib-htmlmin
      dist: {
        files: [{
          expand: true,
          cwd: '<%= project.path.dist %>',
          src: [
            '*.html'
          ],
          dest: '<%= project.path.dist %>'
        }]
      }
    },
    imagemin: {  // grunt-contrib-imagemin
      dist: {
        files: [{
          expand: true,
          cwd: '<%= project.path.client %>/img',
          dest: '<%= project.path.dist %>/img',
          src: '**/*.{gif,jpg,png}'
        }]
      }
    },
    intern: {  // intern
      client: {
        options: {
          config: 'test/intern'
        }
      },
      clientSuiteGet: {
        options: {
          config: 'test/intern',
          suites: ['test/lib/get']
        }
      },
      runner: {
        options: {
          config: 'test/intern',
          runType: 'runner'
        }
      }
    },
    jshint: {  // grunt-contrib-jshint
      options: {
        jshintrc: '.jshintrc'
      },
      client: [
        '<%= project.path.client %>/js/**/*.js',
        '!<%= project.path.client %>/js/node_modules/**/*.js',
        '<%= project.path.client %>/js/node_modules/*.js',
        '<%= project.path.client %>/node_modules/*.js',
      ],
      server: [
        '<%= project.path.server %>/**/*.js'
      ],
      grunt: [
        'Gruntfile.js'
      ]
    },
    karma: {  // grunt-karma
      single: {
        configFile: '<%= project.path.config %>/test/karma-unit.conf.js',
        singleRun: true
      },
      multi: {
        configFile: '<%= project.path.config %>/test/karma-unit.conf.js',
        singleRun: false
      },
      e2e: {
        configFile: '<%= project.path.config %>/test/karma-e2e.conf.js',
        singleRun: true
      }
    },
    less: {  // grunt-contrib-less
      dev: {
        options: {
          dumpLineNumbers: 'comments',
          paths: ['<%= project.path.client %>/less']
        },
        files: {
          '<%= project.path.temp %>/css/main.css': '<%= project.path.client %>/less/index.less',
          '<%= project.path.temp %>/css/static.css': '<%= project.path.client %>/less/_layouts/static/index.less'
        }
      },
      dist: {
        options: {
          paths: ['<%= project.path.client %>/less'],
          compress: true,
          yuicompress: true
        },
        files: {
          '<%= project.path.dist %>/css/main.css': '<%= project.path.client %>/less/index.less',
          '<%= project.path.dist %>/css/static.css': '<%= project.path.client %>/less/_layouts/static/index.less'
        }
      }
    },
    open: {  // grunt-open
      dev: {
        url: 'http://localhost:<%= process.env.PORT || project.server.port %>'
      }
    },
    protractor: {  // grunt-protractor-runner
      options: {
        keepAlive: true,
        noColor: false
      },
      e2e: {
        configFile: '<%= project.path.config %>/test/protractor-e2e.conf.js',
      }
    },
    uglify: {  // grunt-contrib-uglify
      dist: {
        options: {
          beautify: true
        },
        files: _.transform({
          paths: _.map([
            'es5-shim.js',
            'json3.js',
            'modernizr.js'
          ], function (path) {
            return project.path.dist + '/js/vendor/' + path;
          })
        }, function (result, files) {
          _.assign(result, _.object(files, files));
        })
      }
    },
    usemin: {  // grunt-usemin
      options: {
        dirs: ['<%= project.path.dist %>']
      },
      html: ['<%= project.path.dist %>/*.html'],
      css: ['<%= project.path.dist %>/css/{,*/}*.css']
    },
    useminPrepare: {  // grunt-usemin
      options: {
        flow: { steps: { 'js': ['concat'], 'css': ['concat', 'cssmin']}, post: {}},
        dest: '<%= project.path.dist %>'
      },
      html: '<%= project.path.client %>/*.html'
    },
    watch: {  // grunt-contrib-watch
      livereload: {
        options: {
          livereload: project.server.livereload
        },
        files: [
          '<%= project.path.client %>/fonts/{,*/}*',
          '<%= project.path.client %>/img/**/*.{gif,jpg,png}',
          '<%= project.path.server %>/views/**/*.hbs',
          '<%= project.path.static %>/**/*',
          '<%= project.path.temp %>/*.html',
          '<%= project.path.temp %>/css/{,*/}*.css',
          '<%= project.path.temp %>/js/{,*/}*.js'
        ]
      },
      html: {
        files: [
          '<%= project.path.client %>/*.html'
        ],
        tasks: [
          'copy:dev',
          'cachebust:dev'
        ]
      },
      less: {
        files: ['<%= project.path.client %>/less/**/*.less'],
        tasks: ['less:dev']
      },
      js: {
        files: [
          '<%= jshint.client %>',
          '<%= project.path.client %>/js/**/*.html',
          '!<%= project.path.client %>/js/bower_components/**/*.html'
        ],
        tasks: ['browserify2:dev']
      }
    }
  });

  grunt.registerTask('buildDev', [
    'clean:dev',
    'browserify2:dev',
    'less:dev',
    'copy:dev',
    'symlinkDev',
    'cachebust:dev'
  ]);

  grunt.registerTask('buildDist', [
    'jshint',
    'clean:dist',
    'browserify2:dist',
    'less:dist',
    'useminPrepare',
    'htmlmin:dist',
    'imagemin:dist',
    'copy:dist',
    'symlinkDist',
    'cachebust:dist',
    'usemin',
    'uglify:dist'
  ]);

  grunt.registerMultiTask('cachebust', function () {
    this.files.forEach(function (file) {
      file.src.filter(function (filepath) {
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function (filepath) {
        var hash = '' + new Date().getTime(),
            data = grunt.file.read(filepath, { encoding: 'utf-8' });
        grunt.util._.each({
          js: {
            src: /<script.+src=['"](?!http:|https:|\/\/)([^"']+)["']/gm,
            file: /src=['"]([^"']+)["']/m
          },
          css: {
            src: /<link.+href=["'](?!http:|https:|\/\/).*\.css("|\?.*")/gm,
            file: /href=['"]([^"']+)["']/m
          },
          images: {
            src: /<img[^\>]+src=['"](?!http:|https:|\/\/|data:image)([^"']+)["']/gm,
            file: /src=['"]([^"']+)["']/m
          }
        }, function (regex) {
          if (/\.hbs$/.test(filepath)) { return; }
          var matches = data.match(regex.src) || [];
          if (matches.length) {
            console.log(matches);
          }
          matches.forEach(function (snippet) {
            snippet = snippet.substring(0, snippet.length - 1);
            data = data.replace(snippet, snippet.split('?')[0] + '?' + hash);
          });
        });
        if (!/\.hbs$/.test(filepath)) {
          grunt.file.write(filepath, data);
          grunt.log.writeln('"' + filepath + '" busted.');
        }
        // Save hash to file so express server can use the value.
        var cachebustData = {};
        try {
          cachebustData = grunt.file.readJSON('.cachebust');
        } catch (e) {}
        cachebustData[filepath] = hash;
        grunt.file.write('.cachebust', JSON.stringify(cachebustData, null, 2));
        grunt.log.writeln('".cachebust" updated.');
      });
    });
  });

  grunt.registerTask('symlinkDev', function () {
    ['fonts'].forEach(function (dir) {
      var symlinks = require(util.format('./%s/%s/.symlinks', project.path.client, dir));
      _.each(symlinks, function (source, target) {
        source = path.resolve(path.join(project.path.client, dir, source));
        target = path.resolve(path.join(project.path.temp, dir, target));
        wrench.mkdirSyncRecursive(path.join(project.path.temp, dir));
        wrench.copyDirSyncRecursive(source, target);
      });
      console.info('Resolved symlinks: %s', path.resolve(project.path.client, dir));
    });
  });

  grunt.registerTask('symlinkDist', function () {
    ['fonts'].forEach(function (dir) {
      var symlinks = require(util.format('./%s/%s/.symlinks', project.path.client, dir));
      _.each(symlinks, function (source, target) {
        source = path.resolve(path.join(project.path.client, dir, source));
        target = path.resolve(path.join(project.path.dist, dir, target));
        wrench.mkdirSyncRecursive(path.join(project.path.dist, dir));
        wrench.copyDirSyncRecursive(source, target);
      });
      console.info('Resolved symlinks: %s', path.resolve(project.path.dist, dir));
    });
  });

  grunt.registerTask('serverDev', function () {
    grunt.task.run([
      'express',
      'open'
    ]);
    if (process.env.NODE_ENV !== 'heroku' && process.env.NODE_ENV !== 'production') {
      grunt.task.run('watch');
    }
  });

  grunt.registerTask('build', 'buildDist');
  grunt.registerTask('test', [
    'jshint',
    'protractor'
    // 'karma:multi'
  ]);

  // Shortcuts
  grunt.registerTask('b', 'build');
  grunt.registerTask('c', 'clean');
  grunt.registerTask('d', 'buildDev');
  grunt.registerTask('s', 'serverDev');
  grunt.registerTask('t', 'test');

  // Default
  grunt.registerTask('default', ['buildDev', 'serverDev']);
};
<|endoftext|>


<commit_before>const Discord = require('discord.js');
var client = new Discord.Client();
var bot = new Discord.Client();
//-----------------------------------------------------------------------------------------
var Author
var user
var victime
//-----------------------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------
function commandIs(str, msg) { /// this function get rid of the "!" and considers following message as a command
	return msg.content.toUpperCase().startsWith("!" + str);
}
function pluck(array) {
    return array.map(function(item) { return item["name"]; });
}
function hasRole(mem, role) { /// this function checks for user's role
	if(pluck(mem.roles).includes(role)) {
		return true;
	} else {
		return false;
	}
}
//-----------------------------------------------------------------------------------------
client.on('ready', () => {
  console.log('Bot is Online');
});

//-----------------------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------
client.on('message', message => { /// basicaly the start of the bot
	var args = message.content.split(/[ ]+/); /// makes sure that space between command and other is considered as an argument
//-----------------------------------------------------------------------------------------
	///Command using simple or no arguments
  if (commandIs("PING", message)){
  	message.reply('pong');
  }
  if (commandIs("HELP", message)){
  	message.delete() /// deletes the message
  	/// as seen below the character before the "here" is used if you wish to write multiple lines messages
  	message.reply(`Here are the commands availlable for now:
!Help: where you are now.
!Info: gives you infos about the bot.
`)
  }
  if (commandIs("INFO", message)){
  	message.delete()
  	message.channel.spassMessage('This is public bot "Hacker Bot" made by WhiteEyeHackers Dev team. Pre-alpha 1.5.0');
  }
//-----------------------------------------------------------------------------------------
  if (commandIs("SAY", message)){
  	message.delete()
    if (args.length > 1){
    	message.channel.spassMessage(message.author.username + " wants me to say: " + args[1]); /// a showcase of the use of arguments
  	}
  	else
    	message.channel.spassMessage("Error with the command. Usage: `!Say <messageToSay>`");
  }
//-----------------------------------------------------------------------------------------
  if (commandIs("BROADCAST", message)){
  	message.delete()
  	if(hasRole(message.member, "Leutenant") || hasRole(message.member, "Admin") || hasRole(message.member, "Moderator")) { ///a showcase of the use of role chacking
		if (args.length > 1){
  			message.channel.spassMessage(args.join(" ").substring(10));
  		}
  		else{
    		message.channel.spassMessage("Error with the command. Usage: `!Boardcast <messageToSay>`");
        }
   	}
  	else {
  		message.reply("Error, you do not have the proper rank to do so.");
  	}
  }

//-----------------------------------------------------------------------------------------
  /// Commands using one mention
  var input = message.content.toUpperCase() ;
  if (input.startsWith("!SHUT")){ /// example of the use of variables in a message
    user = message.author
    victime = message.mentions.users.first()
    message.delete()
//-----------------------------------------------------------------------------------------
    if(hasRole(message.member, "Owner") || hasRole(message.member, "Staff") || hasRole(message.member, "Admin") || hasRole(message.member, "Developer"))
    {
      message.channel.spassMessage(`!!!MODERATION NOTE!!! ${victime}, please do not spam/flood the chat. This is a warning message, if you still keep doing that thurther measures will be taken. Moderator: ${user}`)
    }
    else
    {
      message.channel.spassMessage(`Hey, who do you think you are ${user}? You'r not an Admin...`)
    }
  }
//-----------------------------------------------------------------------------------------
  if(input.startsWith("!SHOOT"))
  {
    user = message.author
    victime = message.mentions.users.first()
    message.delete()
    message.channel.spassMessage(`${user} does definately not like ${victime}. He takes he's huge 500MAgnum and blows ${victime}'s head. There is really nothing left of ${victime}.`)
  }
//-----------------------------------------------------------------------------------------
	//Get exploits list from db.
	//Not functional
	if(input.startsWith("!WOT"))
  {
const exec = require('child_process').exec;
exec('searchsploit', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);

	function printtochnnel(element, index, array)
	{
		message.channel.spassMessage("Testingar : " + index + " => " + element);
	}
//------------------------------------------------------

//-----------------------------------------------------------------------------------------
	var testing = `${error}`;
	var testingl = testing.length;
	var testingar = testing.length;
//-----------------------------------------------------------------------------------------
	testingar.forEach(printtochnnel);

	var testings = testing.split("\n");
	message.channel.spassMessage(testings[1]);
	message.channel.spassMessage(testingl);
	//message.channel.spassMessage(err.length);
	//message.channel.spassMessage(tempp.toString().length);
	//console.log(tempp.toString().length);

    return;
  }
/*	var testing = "hello";
	var testingl = testing.length;
	var err = `${stdout}`;
	var tempp = (`${stdout}`);
	message.channel.spassMessage(`testingl`);
	message.channel.spassMessage(err.length);
	message.channel.spassMessage(tempp.toString().length);
	console.log(tempp.toString().length);
	alert(`${stdout}`.toString().length);
	console.log(alert(`${stdout}`.toString().length));
	message.channel.spassMessage(alert(`${stdout}`.length));
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
  message.channel.spassMessage(`stdout: ${stdout}`);
  message.channel.spassMessage(`stderr: ${stderr}`);
*/
});

  }

//-----------------------------------------------------------------------------------------
  /// Simple answer command
  if (commandIs("HEY", message)){
    message.delete()
    message.channel.spassMessage("How's it going?");
//--------------------------------------------------------------------
//	var postedmsg = message.content;

  }
	//Assign beginer role to message sender
	if(input.startsWith("!ASSIGN")){
 	 if(input.indexOf("BEGINNER") !== -1){
		 message.member.addRole("254851131551907853");
		 message.channel.sendMessage("User " + message.author + " has been granted role ***Beginner Hacker***");
 	 }
  }
	//Unassign beginer role to message sender
	if(input.startsWith("!UNASSIGN")){
		if(input.indexOf("BEGINNER") !== -1){
			message.member.removeRole("254851131551907853");
			message.channel.sendMessage("User " + message.author + "'s role ***Beginner Hacker*** has been removed");

		}
	}
	if(hasRole(message.member, "Staff") //Check staff role
	{
		//Assign beginer role to mentioned target
		if(input.startsWith("!ASSIGNTO")){
	 		if(input.indexOf("BEGINNER") !== -1){
				victime = message.mentions.users.first()
	 		 message.member.addRole("254851131551907853");
	 		 message.channel.sendMessage("User " + victime + " has been granted role ***Beginner Hacker*** by " + message.author + ".");
			else {
				"ERROR: The desired command is wrong. Make sure you use ```!AssignTo Beginner @<target>```"
			}
	 		}
		else {
				"ERROR: The desired command is wrong. Make sure you use ```!AssignTo Beginner @<target>```"
			}
		}
	}

	if(hasRole(message.member, "Staff") //Check staff role
	{
		//Unassign beginer role to mentioned target
		if(input.startsWith("!UNASSIGN")){
			if(input.indexOf("BEGINNER") !== -1){
				message.member.removeRole("254851131551907853");
	 		 message.channel.sendMessage("User " + victime + "'s role ***Beginner Hacker*** has been removed by " + message.author + ".");
			else {
				 "ERROR: The desired command is wrong. Make sure you use ```!UnassignTo Beginner @<target>```"
			}
		}
		else {
				"ERROR: The desired command is wrong. Make sure you use ```!UnassignTo Beginner @<target>```"
			}
		}
	}

 });

//Sets Guest name to new user
 client.on("guildMemberAdd", (member) => {
	 //member.addRole(293379144052375552);
	 member.setNickname("Guest: " + member.user.username);
 });

client.login('your bot token key here');
<commit_msg>Brackets<commit_after>const Discord = require('discord.js');
var client = new Discord.Client();
var bot = new Discord.Client();
//-----------------------------------------------------------------------------------------
var Author
var user
var victime
//-----------------------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------
function commandIs(str, msg) { /// this function get rid of the "!" and considers following message as a command
	return msg.content.toUpperCase().startsWith("!" + str);
}
function pluck(array) {
    return array.map(function(item) { return item["name"]; });
}
function hasRole(mem, role) { /// this function checks for user's role
	if(pluck(mem.roles).includes(role)) {
		return true;
	} else {
		return false;
	}
}
//-----------------------------------------------------------------------------------------
client.on('ready', () => {
  console.log('Bot is Online');
});

//-----------------------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------
client.on('message', message => { /// basicaly the start of the bot
	var args = message.content.split(/[ ]+/); /// makes sure that space between command and other is considered as an argument
//-----------------------------------------------------------------------------------------
	///Command using simple or no arguments
  if (commandIs("PING", message)){
  	message.reply('pong');
  }
  if (commandIs("HELP", message)){
  	message.delete() /// deletes the message
  	/// as seen below the character before the "here" is used if you wish to write multiple lines messages
  	message.reply(`Here are the commands availlable for now:
!Help: where you are now.
!Info: gives you infos about the bot.
`)
  }
  if (commandIs("INFO", message)){
  	message.delete()
  	message.channel.spassMessage('This is public bot "Hacker Bot" made by WhiteEyeHackers Dev team. Pre-alpha 1.5.0');
  }
//-----------------------------------------------------------------------------------------
  if (commandIs("SAY", message)){
  	message.delete()
    if (args.length > 1){
    	message.channel.spassMessage(message.author.username + " wants me to say: " + args[1]); /// a showcase of the use of arguments
  	}
  	else
    	message.channel.spassMessage("Error with the command. Usage: `!Say <messageToSay>`");
  }
//-----------------------------------------------------------------------------------------
  if (commandIs("BROADCAST", message)){
  	message.delete()
  	if(hasRole(message.member, "Leutenant") || hasRole(message.member, "Admin") || hasRole(message.member, "Moderator")) { ///a showcase of the use of role chacking
		if (args.length > 1){
  			message.channel.spassMessage(args.join(" ").substring(10));
  		}
  		else{
    		message.channel.spassMessage("Error with the command. Usage: `!Boardcast <messageToSay>`");
        }
   	}
  	else {
  		message.reply("Error, you do not have the proper rank to do so.");
  	}
  }

//-----------------------------------------------------------------------------------------
  /// Commands using one mention
  var input = message.content.toUpperCase() ;
  if (input.startsWith("!SHUT")){ /// example of the use of variables in a message
    user = message.author
    victime = message.mentions.users.first()
    message.delete()
//-----------------------------------------------------------------------------------------
    if(hasRole(message.member, "Owner") || hasRole(message.member, "Staff") || hasRole(message.member, "Admin") || hasRole(message.member, "Developer"))
    {
      message.channel.spassMessage(`!!!MODERATION NOTE!!! ${victime}, please do not spam/flood the chat. This is a warning message, if you still keep doing that thurther measures will be taken. Moderator: ${user}`)
    }
    else
    {
      message.channel.spassMessage(`Hey, who do you think you are ${user}? You'r not an Admin...`)
    }
  }
//-----------------------------------------------------------------------------------------
  if(input.startsWith("!SHOOT"))
  {
    user = message.author
    victime = message.mentions.users.first()
    message.delete()
    message.channel.spassMessage(`${user} does definately not like ${victime}. He takes he's huge 500MAgnum and blows ${victime}'s head. There is really nothing left of ${victime}.`)
  }
//-----------------------------------------------------------------------------------------
	//Get exploits list from db.
	//Not functional
	if(input.startsWith("!WOT"))
  {
const exec = require('child_process').exec;
exec('searchsploit', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);

	function printtochnnel(element, index, array)
	{
		message.channel.spassMessage("Testingar : " + index + " => " + element);
	}
//------------------------------------------------------

//-----------------------------------------------------------------------------------------
	var testing = `${error}`;
	var testingl = testing.length;
	var testingar = testing.length;
//-----------------------------------------------------------------------------------------
	testingar.forEach(printtochnnel);

	var testings = testing.split("\n");
	message.channel.spassMessage(testings[1]);
	message.channel.spassMessage(testingl);
	//message.channel.spassMessage(err.length);
	//message.channel.spassMessage(tempp.toString().length);
	//console.log(tempp.toString().length);

    return;
  }
/*	var testing = "hello";
	var testingl = testing.length;
	var err = `${stdout}`;
	var tempp = (`${stdout}`);
	message.channel.spassMessage(`testingl`);
	message.channel.spassMessage(err.length);
	message.channel.spassMessage(tempp.toString().length);
	console.log(tempp.toString().length);
	alert(`${stdout}`.toString().length);
	console.log(alert(`${stdout}`.toString().length));
	message.channel.spassMessage(alert(`${stdout}`.length));
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
  message.channel.spassMessage(`stdout: ${stdout}`);
  message.channel.spassMessage(`stderr: ${stderr}`);
*/
});

  }

//-----------------------------------------------------------------------------------------
  /// Simple answer command
  if (commandIs("HEY", message)){
    message.delete()
    message.channel.spassMessage("How's it going?");
//--------------------------------------------------------------------
//	var postedmsg = message.content;

  }
	//Assign beginer role to message sender
	if(input.startsWith("!ASSIGN")){
 	 if(input.indexOf("BEGINNER") !== -1){
		 message.member.addRole("254851131551907853");
		 message.channel.sendMessage("User " + message.author + " has been granted role ***Beginner Hacker***");
 	 }
  }
	//Unassign beginer role to message sender
	if(input.startsWith("!UNASSIGN")){
		if(input.indexOf("BEGINNER") !== -1){
			message.member.removeRole("254851131551907853");
			message.channel.sendMessage("User " + message.author + "'s role ***Beginner Hacker*** has been removed");

		}
	}
	if(hasRole(message.member, "Staff") //Check staff role
		//Assign beginer role to mentioned target
		if(input.startsWith("!ASSIGNTO")){
	 		if(input.indexOf("BEGINNER") !== -1){
				victime = message.mentions.users.first()
	 		 message.member.addRole("254851131551907853");
	 		 message.channel.sendMessage("User " + victime + " has been granted role ***Beginner Hacker*** by " + message.author + ".");
			else {
				"ERROR: The desired command is wrong. Make sure you use ```!AssignTo Beginner @<target>```"
			}
	 		}
		else {
				"ERROR: The desired command is wrong. Make sure you use ```!AssignTo Beginner @<target>```"
			}
		}
	}

	if(hasRole(message.member, "Staff") //Check staff role
		//Unassign beginer role to mentioned target
		if(input.startsWith("!UNASSIGN")){
			if(input.indexOf("BEGINNER") !== -1){
				message.member.removeRole("254851131551907853");
	 		 message.channel.sendMessage("User " + victime + "'s role ***Beginner Hacker*** has been removed by " + message.author + ".");
			else {
				 "ERROR: The desired command is wrong. Make sure you use ```!UnassignTo Beginner @<target>```"
			}
		}
		else {
				"ERROR: The desired command is wrong. Make sure you use ```!UnassignTo Beginner @<target>```"
			}
		}
	}

 });

//Sets Guest name to new user
 client.on("guildMemberAdd", (member) => {
	 //member.addRole(293379144052375552);
	 member.setNickname("Guest: " + member.user.username);
 });

client.login('your bot token key here');
<|endoftext|>


<commit_before><commit_msg>Fix comment<commit_after><|endoftext|>


<commit_before><commit_msg>add missing whitelist functions<commit_after><|endoftext|>


<commit_before>/**
 * @file   loader.js
 * @brief  loader of html,js,css file
 * @author simpart
 * @note   MIT license
 */
/*** initial ***/
$(function() {
    try {
        tetraring.loader = {};
        tetraring.loader.jsCnt      = new Array(7);
        tetraring.loader.jsList     = new Array();
        tetraring.loader.jsPathList = new Array();
        tetraring.loader.jsCheker   = null;
        tetraring.loader.private    = {};

        var loop = 0;
        for(loop=0; loop < tetraring.loader.jsCnt.length ; loop++) {
            tetraring.loader.jsCnt[loop] = 0;
        }

        /* set javascript loader */
        /**
         * parallel javascript loader
         *
         * @param paths : (array) target javascript file paths
         * @param func : (object) callback function
         * @param prm : (mixed) paramter of callback function
         */
        tetraring.loader.js = function(paths, func, prm) {
            try {
                if( (null == paths) || (paths.length == 0) ) {
                    throw new Error('invalid parameter');
                }
                var pval = prm || null;

                if (0 === tetraring.loader.jsCnt[0]) {
                    tetraring.loader.private.jsElem(0, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[1]) {
                    tetraring.loader.private.jsElem(1, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[2]) {
                    tetraring.loader.private.jsElem(2, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[3]) {
                    tetraring.loader.private.jsElem(3, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[4]) {
                    tetraring.loader.private.jsElem(4, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[5]) {
                    tetraring.loader.private.jsElem(5, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[6]) {
                    tetraring.loader.private.jsElem(6, paths, func, pval);
                } else {
                    throw new Error('burst js loading stack.');
                }
            } catch (e) {
                throw new Error(e.stack);
            }
        }
        /* set css loader */
        /**
         * load css
         *
         * @param path to target css
         */
        tetraring.loader.css = function(path) {
            try {
                $('head').append('<link>');
                css = $('head').children(':last');
                css.attr({
                    rel:  'stylesheet',
                    type: 'text/css',
                    href: path
                });
            } catch (e) {
                throw new Error(e.stack);
            }
        }

        /**
         * brief load html
         *
         * @param hpath : (string) path to html file
         * @param h_id : (string) insert the destination 'id' attribute of html tag
         * @param func : (object) callback function
         */
        tetraring.loader.html = function(h_path, h_id, func, prm) {
            try {
                $.ajax({
                    url      : h_path ,
                    type     : 'GET'  ,
                    cache    : false  ,
                    dataType : 'html' ,
                    async    : false
                })
                .done(function(jqXHR, textStatus, errorThrown) {
                    $( '#' + h_id ).html(jqXHR);
                    if( null != func ) {
                        func(jqXHR, prm);
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    throw new Error();
                })
                .always(function(data, textStatus, errorThrown) {});
            } catch (e) {
                throw new Error(e.stack);
            }
        }

        /* set loader private function */
        tetraring.loader.private.jsElem = function(idx, paths, func, pval) {
            try {
                tetraring.loader.jsCnt[idx] = paths.length;
                var chk_flg = false;
                for(var p_idx in paths) {
                    chk_flg = false;
                    for(var c_idx in tetraring.loader.jsPathList) {
                        if(paths[p_idx] == tetraring.loader.jsPathList[c_idx]) {
                            chk_flg = true;
                            break;
                        }
                    }
                    if(true == chk_flg) {
                        tetraring.loader.jsCnt[idx]--;
                        continue;  // already loaded , next js
                    }
                    // js load
                    tetraring.loader.jsPathList.push( paths[p_idx] );
                    var cnt_idx = idx;
                    $.getScript(paths[p_idx] ,
                        function(src,sts,obj) {
                            try {
                                tetraring.loader.jsCnt[cnt_idx]--;
                            } catch( e ) {alert( e.stack );}
                        }
                    );
                }
                tetraring.loader.private.waitJs(idx, func, pval);
            } catch (e) {
                throw new Error(e.stack);
            }
        };

        tetraring.loader.private.waitJs = function(idx, func, pval) {
            try {
                if( 0 == tetraring.loader.jsCnt[idx] ) {
                    if( null != func ) {
                        if ( null == pval ) {
                            func();
                        } else {
                            func(pval);
                        }
                    }
                    return;
                } else {}
                setTimeout(function (p1, p2, p3) {
                    try {
                        tetraring.loader.private.waitJs(p1, p2, p3);
                    } catch (e) {
                        console.error(e.stack);
                    }
                }, 200, idx, func, pval);
            } catch (e) {
                throw new Error(e.stack);
            }
        }
    } catch (e) {
        console.error(e.stack);
    }
});
/* end of file */
<commit_msg>mod loader<commit_after>/**
 * @file   loader.js
 * @brief  loader of html,js,css file
 * @author simpart
 * @note   MIT license
 */
/*** initial ***/
$(function() {
    try {
        tetraring.loader = {};
        tetraring.loader.jsCnt      = new Array(7);
        tetraring.loader.jsList     = new Array();
        tetraring.loader.jsPathList = new Array();
        tetraring.loader.jsCheker   = null;
        tetraring.loader.private    = {};

        var loop = 0;
        for(loop=0; loop < tetraring.loader.jsCnt.length ; loop++) {
            tetraring.loader.jsCnt[loop] = 0;
        }

        /* set javascript loader */
        /**
         * parallel javascript loader
         *
         * @param paths : (array) target javascript file paths
         * @param func : (object) callback function
         * @param prm : (mixed) paramter of callback function
         */
        tetraring.loader.js = function(paths, func, prm) {
            try {
                if( (null == paths) || (paths.length == 0) ) {
                    throw new Error('invalid parameter');
                }
                var pval = prm || null;

                if (0 === tetraring.loader.jsCnt[0]) {
                    tetraring.loader.private.jsElem(0, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[1]) {
                    tetraring.loader.private.jsElem(1, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[2]) {
                    tetraring.loader.private.jsElem(2, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[3]) {
                    tetraring.loader.private.jsElem(3, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[4]) {
                    tetraring.loader.private.jsElem(4, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[5]) {
                    tetraring.loader.private.jsElem(5, paths, func, pval);
                } else if(0 === tetraring.loader.jsCnt[6]) {
                    tetraring.loader.private.jsElem(6, paths, func, pval);
                } else {
                    throw new Error('burst js loading stack.');
                }
            } catch (e) {
                throw new Error(e.stack);
            }
        }
        /* set css loader */
        /**
         * load css
         *
         * @param path to target css
         */
        tetraring.loader.css = function(path) {
            try {
                $('head').append('<link>');
                css = $('head').children(':last');
                css.attr({
                    rel:  'stylesheet',
                    type: 'text/css',
                    href: path
                });
            } catch (e) {
                throw new Error(e.stack);
            }
        }

        /**
         * brief load html
         *
         * @param hpath : (string) path to html file
         * @param h_id : (string) insert the destination 'id' attribute of html tag
         */
        tetraring.loader.html = function(h_path, h_id) {
            try {
                $.ajax({
                    url      : h_path ,
                    type     : 'GET'  ,
                    cache    : false  ,
                    dataType : 'html' ,
                    async    : false
                })
                .done(function(jqXHR, textStatus, errorThrown) {
                    $( '#' + h_id ).html(jqXHR);
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    throw new Error();
                })
                .always(function(data, textStatus, errorThrown) {});
            } catch (e) {
                throw new Error(e.stack);
            }
        }

        /* set loader private function */
        tetraring.loader.private.jsElem = function(idx, paths, func, pval) {
            try {
                tetraring.loader.jsCnt[idx] = paths.length;
                var chk_flg = false;
                for(var p_idx in paths) {
                    chk_flg = false;
                    for(var c_idx in tetraring.loader.jsPathList) {
                        if(paths[p_idx] == tetraring.loader.jsPathList[c_idx]) {
                            chk_flg = true;
                            break;
                        }
                    }
                    if(true == chk_flg) {
                        tetraring.loader.jsCnt[idx]--;
                        continue;  // already loaded , next js
                    }
                    // js load
                    tetraring.loader.jsPathList.push( paths[p_idx] );
                    var cnt_idx = idx;
                    $.getScript(paths[p_idx] ,
                        function(src,sts,obj) {
                            try {
                                tetraring.loader.jsCnt[cnt_idx]--;
                            } catch( e ) {alert( e.stack );}
                        }
                    );
                }
                tetraring.loader.private.waitJs(idx, func, pval);
            } catch (e) {
                throw new Error(e.stack);
            }
        };

        tetraring.loader.private.waitJs = function(idx, func, pval) {
            try {
                if( 0 == tetraring.loader.jsCnt[idx] ) {
                    if( null != func ) {
                        if ( null == pval ) {
                            func();
                        } else {
                            func(pval);
                        }
                    }
                    return;
                } else {}
                setTimeout(function (p1, p2, p3) {
                    try {
                        tetraring.loader.private.waitJs(p1, p2, p3);
                    } catch (e) {
                        console.error(e.stack);
                    }
                }, 200, idx, func, pval);
            } catch (e) {
                throw new Error(e.stack);
            }
        }
    } catch (e) {
        console.error(e.stack);
    }
});
/* end of file */
<|endoftext|>


<commit_before>// @flow

import HtmlHighlighter from './htmlhighlighter';

export type LoggingArgs = Array<any>;

/**
 * Logging class
 *
 * Emits debug and log console output when the associated HTML Highlighter class's `debug` static
 * attribute is `true`.  Also ensures all messages contain the 'html-highlighter: ' prefix.
 */
class Logger {
  highlighter: HtmlHighlighter | null;

  init(highlighter: HtmlHighlighter): void {
    this.highlighter = highlighter;
  }

  debug(...args: LoggingArgs): void {
    this.assert();
    if ((this.highlighter: any).debug) {
      this.emit('debug', args);
    }
  }

  log(...args: LoggingArgs): void {
    this.assert();
    if ((this.highlighter: any).debug) {
      this.emit('log', args);
    }
  }

  info(...args: LoggingArgs): void {
    this.emit('info', args);
  }

  warn(...args: LoggingArgs): void {
    this.emit('warn', args);
  }

  error(...args: LoggingArgs): void {
    this.emit('error', args);
  }

  exception(...args: LoggingArgs): void {
    args = this.prepend(args, 'exception occurred', 'unknown exception occurred');
    this.emit('error', args);
  }

  prepend(args: LoggingArgs, str: string, strIfEmpty: ?string): LoggingArgs {
    if (args.length === 0) {
      return [strIfEmpty || str];
    }

    const first = args[0];
    if (typeof first === 'string') {
      args[0] = `${str}: ${first}`;
    }

    return args;
  }

  emit(type: string, args: LoggingArgs): void {
    const fn = console[type];
    if (fn == null) {
      throw new Error(`Unknown \`console\` function or unavailable: ${type}`);
    }

    fn.apply(window, this.prepend(args, 'html-highlighter'));
  }

  assert(): void {
    if (this.highlighter == null) {
      throw new Error('Not initialized yet with valid HTML Highlighter instance');
    }
  }
}

export default new Logger();
<commit_msg>src: execute console function in correct context<commit_after>// @flow

import HtmlHighlighter from './htmlhighlighter';

export type LoggingArgs = Array<any>;

/**
 * Logging class
 *
 * Emits debug and log console output when the associated HTML Highlighter class's `debug` static
 * attribute is `true`.  Also ensures all messages contain the 'html-highlighter: ' prefix.
 */
class Logger {
  highlighter: HtmlHighlighter | null;

  init(highlighter: HtmlHighlighter): void {
    this.highlighter = highlighter;
  }

  debug(...args: LoggingArgs): void {
    this.assert();
    if ((this.highlighter: any).debug) {
      this.emit('debug', args);
    }
  }

  log(...args: LoggingArgs): void {
    this.assert();
    if ((this.highlighter: any).debug) {
      this.emit('log', args);
    }
  }

  info(...args: LoggingArgs): void {
    this.emit('info', args);
  }

  warn(...args: LoggingArgs): void {
    this.emit('warn', args);
  }

  error(...args: LoggingArgs): void {
    this.emit('error', args);
  }

  exception(...args: LoggingArgs): void {
    args = this.prepend(args, 'exception occurred', 'unknown exception occurred');
    this.emit('error', args);
  }

  prepend(args: LoggingArgs, str: string, strIfEmpty: ?string): LoggingArgs {
    if (args.length === 0) {
      return [strIfEmpty || str];
    }

    const first = args[0];
    if (typeof first === 'string') {
      args[0] = `${str}: ${first}`;
    }

    return args;
  }

  emit(type: string, args: LoggingArgs): void {
    const fn = console[type];
    if (fn != null) {
      fn.apply(console, this.prepend(args, 'html-highlighter'));
    }
  }

  assert(): void {
    if (this.highlighter == null) {
      throw new Error('Not initialized yet with valid HTML Highlighter instance');
    }
  }
}

export default new Logger();
<|endoftext|>


<commit_before>if (process.env.MOCHA === '1') {
  // If testing from CLI, use noop logger, to not interfere with the mocha reporter
  // (see issues mochajs/mocha#1998, mochajs/mocha#2107, etc.)

  // code only uses these methods, so this should be enough
  global.logger = {error () {}, warn () {}, info () {}}
} else {
  // Else make a stderr-only console, so that you can redirect the CLI output to a
  // file (see issue #73)
  global.logger = new console.Console(process.stderr)
}
<commit_msg>[package:test] Fix case for codecov tools<commit_after>/* istanbul ignore else: coverage tools always in testing environment */
if (process.env.MOCHA === '1') {
  // If testing from CLI, use noop logger, to not interfere with the mocha reporter
  // (see issues mochajs/mocha#1998, mochajs/mocha#2107, etc.)

  // code only uses these methods, so this should be enough
  global.logger = {error () {}, warn () {}, info () {}}
} else {
  // Else make a stderr-only console, so that you can redirect the CLI output to a
  // file (see issue #73)
  global.logger = new console.Console(process.stderr)
}
<|endoftext|>


<commit_before>import chalk from 'chalk';

export function message(msg) {
  console.log(`${chalk.bold.gray(msg)}`);
}

export function info(msg, iconCode) {
  const icon = String.fromCodePoint(iconCode ? iconCode : 0x1F4E2);
  console.log(`${icon}  ${chalk.bold.underline.blue('Info:')} --> ${chalk.bold.blue(msg)}`);
}

export function error(msg, iconCode) {
  const icon = String.fromCodePoint(iconCode ? iconCode : 0x2757);
  console.log(`${icon}  ${chalk.bold.underline.red('Error:')} --> ${chalk.bold.red(msg)}`);
}

export function warning(msg, iconCode) {
  const icon = String.fromCodePoint(iconCode ? iconCode : 0x26A0);
  console.log(`${icon}  ${chalk.bold.underline.yellow('Warning:')} --> ${chalk.bold.yellow(msg)}`);
}

export function success(msg, iconCode) {
  const icon = String.fromCodePoint(iconCode ? iconCode : 0x1F44C);
  console.log(`${icon}  ${chalk.bold.underline.green('Success:')} --> ${chalk.bold.green(msg)}`);
}
<commit_msg>Changes error log.<commit_after>import chalk from 'chalk';

export function message(msg) {
  console.log(`${chalk.bold.gray(msg)}`);
}

export function info(msg, iconCode) {
  const icon = String.fromCodePoint(iconCode ? iconCode : 0x1F4E2);
  console.log(`${icon}  ${chalk.bold.underline.blue('Info:')} --> ${chalk.bold.blue(msg)}`);
}

export function error(msg, iconCode) {
  const icon = String.fromCodePoint(iconCode ? iconCode : 0x2757);
  console.log(`${icon} ${chalk.bold.red(msg)}`);
}

export function warning(msg, iconCode) {
  const icon = String.fromCodePoint(iconCode ? iconCode : 0x26A0);
  console.log(`${icon}  ${chalk.bold.underline.yellow('Warning:')} --> ${chalk.bold.yellow(msg)}`);
}

export function success(msg, iconCode) {
  const icon = String.fromCodePoint(iconCode ? iconCode : 0x1F44C);
  console.log(`${icon}  ${chalk.bold.underline.green('Success:')} --> ${chalk.bold.green(msg)}`);
}
<|endoftext|>


<commit_before>/**
 * @file
 * Establishes an error logging service for Kalabox using the Winston module.
 *
 * Copyright 2013 Kalamuna LLC
 */

// Dependencies:
var winston = require('winston'),
    flow = require('nue').flow,
    as = require('nue').as,
    fs = require('fs'),
    exec = require('child_process').exec,
    config = require('./config');

// "Constants":
var KALABOX_DIR = config.get('KALABOX_DIR'),
    LOG_FILE = KALABOX_DIR + 'kalabox.log';

// Create a new logger instance that writes to the console and log file.
exports = module.exports = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)(),
    new (winston.transports.File)({ filename: LOG_FILE })
  ]
});

// Connect to Socket.io so we can emit an error event.
var socket;
exports.on('logging', function(transport, level, msg, meta) {
  // Send message to frontend via event on error.
  if (level == 'error') {
    socket.emit('appError');
  }
});

/**
 * Initializes the logger, creating the log file if it doesn't exists.
 *
 * @param function callback
 *   Function to call once the initialization completes.
 * @param object io
 *   IO event emitter dependency.
 */
exports.initialize = flow('initialize')(
  function initialize0(callback, io) {
    this.data.callback = callback;
    // Configure Socket.io dependency.
    socket = io.sockets;
    // Check if Kalabox directory exists.
    fs.exists(KALABOX_DIR, this.async(as(0)));
  },
  // If directory doesn't exist, create it.
  function initialize1(exists) {
    if (!exists) {
      exec('mkdir -p ' + KALABOX_DIR, this.async());
    }
    else {
      this.next();
    }
  },
  // Check if log file exists.
  function initialize2() {
    fs.exists(LOG_FILE, this.async(as(0)));
  },
  // If log file doesn't exist, create it.
  function initialize3(exists) {
    if (!exists) {
      fs.writeFile(LOG_FILE, '### Kalabox Log ###\n\n', this.async());
    }
    else {
      this.next();
    }
  },
  function initializeEnd() {
    if (this.err) {
      exports.error('Error initializing logging service: ' + this.err.message);
      this.err = null;
    }
    // Set logger to handle uncaught exceptions too.
    process.on('uncaughtException', function(err) {
      exports.error('Uncaught Exception\n' + '\nStack:\n' + err.stack);
    });

    this.data.callback();
    this.next();
  }
);

/**
 * Loads contents of the log file.
 *
 * @param function callback
 *   Function to call with the contents of the log file.
 */
exports.loadLog = flow('loadLog')(
  // Check if log file exists.
  function loadLog0(callback) {
    this.data.callback = callback;
    fs.exists(LOG_FILE, this.async(as(0)));
  },
  // Read in the file.
  function loadLog1(exists) {
    if (!exists) {
      this.end();
    }
    else {
      fs.readFile(LOG_FILE, this.async());
    }
  },
  // Return log contents.
  function loadLogEnd(contents) {
    if (this.err) {
      exports.error('Error loading log file: ' + this.err.message);
      this.err = null;
      this.next();
      this.data.callback();
      return;
    }
    if (contents) {
      this.data.callback(contents);
    }
  }
);
<commit_msg>Switched error logging output to human-readable.<commit_after>/**
 * @file
 * Establishes an error logging service for Kalabox using the Winston module.
 *
 * Copyright 2013 Kalamuna LLC
 */

// Dependencies:
var winston = require('winston'),
    flow = require('nue').flow,
    as = require('nue').as,
    fs = require('fs'),
    exec = require('child_process').exec,
    config = require('./config');

// "Constants":
var KALABOX_DIR = config.get('KALABOX_DIR'),
    LOG_FILE = KALABOX_DIR + 'kalabox.log';

// Create a new logger instance that writes to the console and log file.
exports = module.exports = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)(),
    new (winston.transports.File)({ filename: LOG_FILE, json: false })
  ]
});

// Connect to Socket.io so we can emit an error event.
var socket;
exports.on('logging', function(transport, level, msg, meta) {
  // Send message to frontend via event on error.
  if (level == 'error') {
    socket.emit('appError');
  }
});

/**
 * Initializes the logger, creating the log file if it doesn't exists.
 *
 * @param function callback
 *   Function to call once the initialization completes.
 * @param object io
 *   IO event emitter dependency.
 */
exports.initialize = flow('initialize')(
  function initialize0(callback, io) {
    this.data.callback = callback;
    // Configure Socket.io dependency.
    socket = io.sockets;
    // Check if Kalabox directory exists.
    fs.exists(KALABOX_DIR, this.async(as(0)));
  },
  // If directory doesn't exist, create it.
  function initialize1(exists) {
    if (!exists) {
      exec('mkdir -p ' + KALABOX_DIR, this.async());
    }
    else {
      this.next();
    }
  },
  // Check if log file exists.
  function initialize2() {
    fs.exists(LOG_FILE, this.async(as(0)));
  },
  // If log file doesn't exist, create it.
  function initialize3(exists) {
    if (!exists) {
      fs.writeFile(LOG_FILE, '### Kalabox Log ###\n\n', this.async());
    }
    else {
      this.next();
    }
  },
  function initializeEnd() {
    if (this.err) {
      exports.error('Error initializing logging service: ' + this.err.message);
      this.err = null;
    }
    // Set logger to handle uncaught exceptions too.
    process.on('uncaughtException', function(err) {
      exports.error('Uncaught Exception\n' + '\nStack:\n' + err.stack);
    });

    this.data.callback();
    this.next();
  }
);

/**
 * Loads contents of the log file.
 *
 * @param function callback
 *   Function to call with the contents of the log file.
 */
exports.loadLog = flow('loadLog')(
  // Check if log file exists.
  function loadLog0(callback) {
    this.data.callback = callback;
    fs.exists(LOG_FILE, this.async(as(0)));
  },
  // Read in the file.
  function loadLog1(exists) {
    if (!exists) {
      this.end();
    }
    else {
      fs.readFile(LOG_FILE, this.async());
    }
  },
  // Return log contents.
  function loadLogEnd(contents) {
    if (this.err) {
      exports.error('Error loading log file: ' + this.err.message);
      this.err = null;
      this.next();
      this.data.callback();
      return;
    }
    if (contents) {
      this.data.callback(contents);
    }
  }
);
<|endoftext|>


<commit_before>/*jshint esversion: 6 */
"use strict";

const assert               = require('assert');

const lua                  = require('./lua.js');
const lobject              = require('./lobject.js');
const ldo                  = require('./ldo.js');
const lapi                 = require('./lapi.js');
const nil                  = ldo.nil;
const luaD_rawrunprotected = ldo.luaD_rawrunprotected;
const luaT_init            = require('./ltm.js').luaT_init;
const CT                   = lua.constant_types;
const LUA_MULTRET          = lua.LUA_MULTRET;
const TS                   = lua.thread_status;
const LUA_NUMTAGS          = lua.LUA_NUMTAGS;

const BASIC_STACK_SIZE = 2 * lua.LUA_MINSTACK;

class CallInfo {

    constructor(funcOff, func, top, base, previous, next) {
        this.func = func;
        this.funcOff = funcOff;
        this.top = top;
        this.previous = previous;
        this.next = next;
        this.pcOff = 0;
        this.u = {
            l: {  /* only for Lua functions */
                base: base,  /* base for this function */
                savedpc: []
            },
            c: {  /* only for JS functions */
                k: null,  /* continuation in case of yields */
                old_errfunc: null,
                ctx: null  /* context info. in case of yields */
            }
        };
        this.nresults = 0;
        this.callstatus = 0;
    }

}

class lua_State extends lobject.TValue {

    constructor() {
        super(CT.LUA_TTHREAD, null);
        this.base_ci = new CallInfo(); // Will be populated later
        this.top = 0;
        this.ci = null;
        this.ciOff = null;
        this.stack = [];
        this.openupval = [];
        this.status = TS.LUA_OK;
        this.next = null;
        this.twups = [this];
        this.errorJmp = null;
        this.nny = 1;
        this.errfunc = 0;

        this.value = this;
    }

}

class global_State {

    constructor(L) {
        this.mainthread = L;
        this.strt = new Map();
        this.l_registry = nil;
        this.panic = null;
        this.version = null;
        this.twups = [];
        this.mt = new Array(LUA_NUMTAGS);
    }

    intern(stringArray) {
        // TODO: when weak value maps are available
        // let key = stringArray.map(e => `${e}|`).join('');

        // if (!this.strt.has(key))
        //     this.strt.set(key, new lobject.TValue(CT.LUA_TLNGSTR, stringArray));

        // return this.strt.get(key);

        return new lobject.TValue(CT.LUA_TLNGSTR, stringArray);
    }

}

const stack_init = function(L1, L) {
    L1.stack = new Array(BASIC_STACK_SIZE); // TODO: for now we don't care about the stack size
    L1.top = 0;
    let ci = L1.base_ci;
    ci.next = ci.previous = null;
    ci.callstatus = 0;
    ci.func = L1.stack[L1.top];
    ci.funcOff = L1.top;
    L1.stack[L1.top++] = nil;
    ci.top = L1.top + lua.LUA_MINSTACK;
    L1.ci = ci;
};

/*
** Create registry table and its predefined values
*/
const init_registry = function(L, g) {
    let registry = new lobject.Table();
    g.l_registry = registry;
    registry.value.set(lua.LUA_RIDX_MAINTHREAD - 1, L);
    registry.value.set(lua.LUA_RIDX_GLOBALS - 1, new lobject.Table());
};

/*
** open parts of the state that may cause memory-allocation errors.
** ('g->version' !== NULL flags that the state was completely build)
*/
const f_luaopen = function(L) {
    let g = L.l_G;
    stack_init(L, L);
    init_registry(L, g);
    luaT_init(L);
    g.version = lapi.lua_version(null);
};

const preinit_thread = function(L, g) {
    L.l_G = g;
    L.stack = [];
    L.ci = null;
    L.nci = 0;
    L.twups = [L];  /* thread has no upvalues */
    L.errorJmp = null;
    L.nCcalls = 0;
    L.hook = null;
    L.hookmask = 0;
    L.basehookcount = 0;
    L.allowhook = 1;
    L.hookcount = L.basehookcount;
    L.openupval = [];
    L.nny = 1;
    L.status = TS.LUA_OK;
    L.errfunc = 0;
};

const lua_newthread = function(L) {
    let g = L.l_G;
    let L1 = new lua_State();
    L.stack[L.top++] = L1;
    assert(L.top <= L.ci.top, "stack overflow");
    preinit_thread(L1, g);
    L1.hookmask = L.hookmask;
    L1.basehookcount = L.basehookcount;
    L1.hook = L.hook;
    L1.hookcount = L1.basehookcount;
    stack_init(L1, L);
    return L1;
};

const lua_newstate = function() {
    let L = new lua_State();
    let g = new global_State(L);

    preinit_thread(L, g);

    if (luaD_rawrunprotected(L, f_luaopen, null) !== TS.LUA_OK) {
        L = null;
    }

    return L;
};

module.exports.lua_State      = lua_State;
module.exports.CallInfo       = CallInfo;
module.exports.CIST_OAH       = (1<<0);  /* original value of 'allowhook' */
module.exports.CIST_LUA       = (1<<1);  /* call is running a Lua function */
module.exports.CIST_HOOKED    = (1<<2);  /* call is running a debug hook */
module.exports.CIST_FRESH     = (1<<3);  /* call is running on a fresh invocation of luaV_execute */
module.exports.CIST_YPCALL    = (1<<4);  /* call is a yieldable protected call */
module.exports.CIST_TAIL      = (1<<5);  /* call was tail called */
module.exports.CIST_HOOKYIELD = (1<<6);  /* last hook called yielded */
module.exports.CIST_LEQ       = (1<<7);  /* using __lt for __le */
module.exports.CIST_FIN       = (1<<8);   /* call is running a finalizer */
module.exports.lua_newstate   = lua_newstate;
module.exports.lua_newthread  = lua_newthread;<commit_msg>lstate: Don't localise ldo.js fields<commit_after>/*jshint esversion: 6 */
"use strict";

const assert               = require('assert');

const lua                  = require('./lua.js');
const lobject              = require('./lobject.js');
const ldo                  = require('./ldo.js');
const lapi                 = require('./lapi.js');
const luaT_init            = require('./ltm.js').luaT_init;
const CT                   = lua.constant_types;
const LUA_MULTRET          = lua.LUA_MULTRET;
const TS                   = lua.thread_status;
const LUA_NUMTAGS          = lua.LUA_NUMTAGS;

const BASIC_STACK_SIZE = 2 * lua.LUA_MINSTACK;

class CallInfo {

    constructor(funcOff, func, top, base, previous, next) {
        this.func = func;
        this.funcOff = funcOff;
        this.top = top;
        this.previous = previous;
        this.next = next;
        this.pcOff = 0;
        this.u = {
            l: {  /* only for Lua functions */
                base: base,  /* base for this function */
                savedpc: []
            },
            c: {  /* only for JS functions */
                k: null,  /* continuation in case of yields */
                old_errfunc: null,
                ctx: null  /* context info. in case of yields */
            }
        };
        this.nresults = 0;
        this.callstatus = 0;
    }

}

class lua_State extends lobject.TValue {

    constructor() {
        super(CT.LUA_TTHREAD, null);
        this.base_ci = new CallInfo(); // Will be populated later
        this.top = 0;
        this.ci = null;
        this.ciOff = null;
        this.stack = [];
        this.openupval = [];
        this.status = TS.LUA_OK;
        this.next = null;
        this.twups = [this];
        this.errorJmp = null;
        this.nny = 1;
        this.errfunc = 0;

        this.value = this;
    }

}

class global_State {

    constructor(L) {
        this.mainthread = L;
        this.strt = new Map();
        this.l_registry = ldo.nil;
        this.panic = null;
        this.version = null;
        this.twups = [];
        this.mt = new Array(LUA_NUMTAGS);
    }

    intern(stringArray) {
        // TODO: when weak value maps are available
        // let key = stringArray.map(e => `${e}|`).join('');

        // if (!this.strt.has(key))
        //     this.strt.set(key, new lobject.TValue(CT.LUA_TLNGSTR, stringArray));

        // return this.strt.get(key);

        return new lobject.TValue(CT.LUA_TLNGSTR, stringArray);
    }

}

const stack_init = function(L1, L) {
    L1.stack = new Array(BASIC_STACK_SIZE); // TODO: for now we don't care about the stack size
    L1.top = 0;
    let ci = L1.base_ci;
    ci.next = ci.previous = null;
    ci.callstatus = 0;
    ci.func = L1.stack[L1.top];
    ci.funcOff = L1.top;
    L1.stack[L1.top++] = ldo.nil;
    ci.top = L1.top + lua.LUA_MINSTACK;
    L1.ci = ci;
};

/*
** Create registry table and its predefined values
*/
const init_registry = function(L, g) {
    let registry = new lobject.Table();
    g.l_registry = registry;
    registry.value.set(lua.LUA_RIDX_MAINTHREAD - 1, L);
    registry.value.set(lua.LUA_RIDX_GLOBALS - 1, new lobject.Table());
};

/*
** open parts of the state that may cause memory-allocation errors.
** ('g->version' !== NULL flags that the state was completely build)
*/
const f_luaopen = function(L) {
    let g = L.l_G;
    stack_init(L, L);
    init_registry(L, g);
    luaT_init(L);
    g.version = lapi.lua_version(null);
};

const preinit_thread = function(L, g) {
    L.l_G = g;
    L.stack = [];
    L.ci = null;
    L.nci = 0;
    L.twups = [L];  /* thread has no upvalues */
    L.errorJmp = null;
    L.nCcalls = 0;
    L.hook = null;
    L.hookmask = 0;
    L.basehookcount = 0;
    L.allowhook = 1;
    L.hookcount = L.basehookcount;
    L.openupval = [];
    L.nny = 1;
    L.status = TS.LUA_OK;
    L.errfunc = 0;
};

const lua_newthread = function(L) {
    let g = L.l_G;
    let L1 = new lua_State();
    L.stack[L.top++] = L1;
    assert(L.top <= L.ci.top, "stack overflow");
    preinit_thread(L1, g);
    L1.hookmask = L.hookmask;
    L1.basehookcount = L.basehookcount;
    L1.hook = L.hook;
    L1.hookcount = L1.basehookcount;
    stack_init(L1, L);
    return L1;
};

const lua_newstate = function() {
    let L = new lua_State();
    let g = new global_State(L);

    preinit_thread(L, g);

    if (ldo.luaD_rawrunprotected(L, f_luaopen, null) !== TS.LUA_OK) {
        L = null;
    }

    return L;
};

module.exports.lua_State      = lua_State;
module.exports.CallInfo       = CallInfo;
module.exports.CIST_OAH       = (1<<0);  /* original value of 'allowhook' */
module.exports.CIST_LUA       = (1<<1);  /* call is running a Lua function */
module.exports.CIST_HOOKED    = (1<<2);  /* call is running a debug hook */
module.exports.CIST_FRESH     = (1<<3);  /* call is running on a fresh invocation of luaV_execute */
module.exports.CIST_YPCALL    = (1<<4);  /* call is a yieldable protected call */
module.exports.CIST_TAIL      = (1<<5);  /* call was tail called */
module.exports.CIST_HOOKYIELD = (1<<6);  /* last hook called yielded */
module.exports.CIST_LEQ       = (1<<7);  /* using __lt for __le */
module.exports.CIST_FIN       = (1<<8);   /* call is running a finalizer */
module.exports.lua_newstate   = lua_newstate;
module.exports.lua_newthread  = lua_newthread;<|endoftext|>


<commit_before>(function(){
	"use strict";

	if(!window.ontouchstart){return;}
	const _=function(){
		let type=function(obj){
   			//'boolean', 'number', 'string', 'function', 'array', 'date', 'regexp', 'object', 'error'
			return obj == null ? String(obj) : {}.toString.call(obj).toLowerCase().replace(/\[object\s|\]/g, '')|| "object";
		},
		toArray=function(arr){
			if(!arr) return [];
			return [].slice.call(arr,0);
		},
		isString=function(str){
			return type(str)==="string";
		},
		isArray=Array.isArray||function(arr) {
			return type(arr) === 'array';
		},
		isFunction=function(value) {
			return type(value) === "function";
		},
		isObject=function(obj) {
			return type(obj) === "object";
		};
   		return {
   			type,
   			toArray,
   			isString,
   			isArray,
   			isFunction,
   			isObject,
   		};
	}();

	const each=function(obj,callback){
		let len=0,i=0;
		if(!obj){return;}
		if(_.isArray(obj)){
			for(len=obj.length;i<len;i++){
				let val=callback.call(obj[i],i,obj[i]);
				if(val===false) break;
			}
		}else if(_.isObject(obj)){
			for(i in obj){
				if(obj.hasOwnProperty(i)){
					let val=callback.call(obj[i],i,obj[i]);
					if(val===false) break;
				}
			}
		}else{
			throw Error("参数格式错误")
		}
	};

	const extend = function(obj) {
		each(slice.call(arguments,1), function(i,value) {
			for(let prop in value) {
				obj[prop] = value[prop];
			}
		});
		return obj;
    };

	//console.log(_.isArray([]),_.isObject({}),_.isFunction(function(){}),_.isString(""));

	extend(_,{
		/**
		 * 生成uuid
		 * @return {String} uuid
		 */
		uuid(){
			return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
				let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
				return v.toString(16);
			});
		},
		each,
		extend,
		/**
		 * 获取当前时间距1970/1/1时间戳
		 * @return {Number}	时间戳
		 */
		getTime:(){
			return +new Date();
		},
		/**
		 * 获取坐标点信息
		 * @param {Object} event 对象
		 * @return {Object}	坐标点信息
		 */
		getPosInfo(event){
			let _touches=event.touches;
			if(_touches||_touches.length===0){
				return;
			}
			return {
				pageX:event.touches[0].pageX,
				pageY:event.touches[0].pageY,
				clientX:event.touches[0].clientX||0,
				clientY:event.touches[0].clientY||0
			}
		},
		/**
		 * 获取划动方向
		 * @param {Number} sX 起始点x坐标
		 * @param {Number} sY 起始点y坐标
		 * @param {Number} eX 结束点x坐标
		 * @param {Number} eY 结束点y坐标
		 * @return {String}	direction 方向
		 */
		getDirection(sX,sY,eX,eY){
			let [xRes,xResAbs]=[sX-eX,Math.abs(sX-eX)];
			let [yRes,yResAbs]=[sY-eY,Math.abs(sY-eY)];
			let direction="";

			if(xResAbs>=yResAbs&&xResAbs>25){
				direction=(xRes>0)?"Right":"Left";
			}else if(yResAbs>xResAbs&&yResAbs>25){
				direction=(yRes>0?"Down":"Up")
			}
			return direction;
		},
		/**
		 * 获取两点之间距离
		 * @param {Number} sX 起始点x坐标
		 * @param {Number} sY 起始点y坐标
		 * @param {Number} eX 结束点x坐标
		 * @param {Number} eY 结束点y坐标
		 * @return {Number}
		 */
		getDistance:(sX,sY,eX,eY)=>Math.sqrt(Math.pow(sX-eX,2)+Math.pow(sY-eY,2)),
		/**
		 * 获取长度
		 * @param {Object} v 坐标点
		 * @return {Number}
		 */
		getLength:v=>Math.sqrt(v.x*v.x+v.y*v.y),
		/**
		 * 叉乘
		 * @param {Object} v1 坐标点
		 * @param {Object} v2 坐标点
		 * @return {Number}
		 */
		cross:(v1,v2)=>v1.x*v2.y-v1.y*v2.x,
		/**
		 * 取向量
		 * @param {Number} sX 起始点x坐标
		 * @param {Number} sY 起始点y坐标
		 * @param {Number} eX 结束点x坐标
		 * @param {Number} eY 结束点y坐标
		 * @return {Number}
		 */
		getVector:(sX,sY,eX,eY)=>sX*eX+sY*eY,
		/**
		 * 获取角度 a*b=|a|*|b|*cos(deg); a*b=x1*x2+y1*y2
		 * @param {Object} v1 坐标点
		 * @param {Object} v2 坐标点
		 * @return {Number} Math.acos(r);
		 *
		 */
		getAngle(v1,v2){
			let mr=this.getLength(v1)*this.getLength(v2);
			if(mr===0){return 0;}

			let r=this.getVector(v1.x,v1.y,v2.x,v2.y)/mr;
			if(v>1){
				r=1;
			}
			return Math.acos(r);
		},
		/**
		 * 获取旋转的角度
		 * @param {Object} v1 坐标点
		 * @param {Object} v2 坐标点
		 * @return {Number} 角度值
		 */
		getRotateAngle(v1,v2){
			let angle=this.getAngle(v1,v2);
			if(this.cross(v1,v2)>0){
				angle*=-1;
			}
			return angle*180/Math.PI;
		},

		/**
		 * 绑定事件
		 * @param {Element} el
		 * @param {String} type
		 * @param {Function} fn
		 */
		bind(el,type,fn){
			el.addEventListener ? el.addEventListener(type, fn, false) : el.attachEvent("on" + type, fn);
		},
		/**
		 * 解绑事件
		 * @param {Element} el
		 * @param {String} type
		 * @param {Function} fn
		 */
		unBind(el,type,fn){
			el.removeEventListener ? el.removeEventListener(type, fn, false) : el.detachEvent("on" + type, fn);
		},
		/**
		 * 事件对象
		 * @param {Object} event
		 * @param {Object} obj
		 * @return {Object} new Event
		 */
		wrapEvent(ev,obj){
			let res={
				touches:ev.touches,
				type:ev.type
			}
			if(this.isObject(obj)){
				res=this.extend(res,obj)
			}
			return res;
		},
		/**
		 * 元素A元素是否包含B元素
		 * @param {Element} A
		 * @param {Element} B
		 */
		contains:(A,B)=>A.contains(B)

	});

	var Event=function(){
		let storeEvents={};
		return{
			/**
			 * add an event handler
			 * @param {String} type
			 * @param {String|Function} el
			 * @param {Function} handler
			 */
			add(type,el,handler){
				let selector=el,
					len=arguments.length,
					finalObject={},
					_type;

				//Event.add("swipe",function(){});
				if(_.isString(el)){
					el=document.querySelectorAll(el);
				}
				if(len===2 && _.isFunction(el)){

					finalObject={
						//selector:"",
						//el:null,
						handler:el
					};

				}else if(len===3 && el instanceof HTMLElement || el instanceof NodeList && _.isFunction(handler)){
					//Event.add("swipe","#div",function(ev){})

					_type=_.type(el);

					finalObject={
						type:_type,
						selector,
						el:_type==="nodelist"?_.toArray(el):el,
						handler
					}

				}

				storeEvents[type]||(storeEvents[type]=[]);
				storeEvents[type].push(finalObject);
			},
			/**
			 * remove an event handle
			 * @param {Style} type
			 * @param {String|Function} selector
			 */
			remove(type,selector){
				let len=arguments.length;
				if(_.isString(type) && _.isArray(storeEvent[type]) && storeEvents[type].length){
					if(len===1){
						storeEvents[type]=[];
					}else if(len===2){
						storeEvents[type]=storeEvents[type].filter(item => !(item.selector===selector || !_.isString(selector) && item.selector.isEqualNode(selector)))
					}

				}
			},
			/**
			 * trigger an event handle
			 * @param {String} type
			 * @param {DocumentElement} el
			 * @param {type} argument
			 */
			trigger(type,el,argument){
				let len=arguments.length;

				//Event.trigger("swipe",document.querySelector("#div"),{...})
				if(len===3 && _.isArray(storeEvents[type]) && storeEvents[type].length){
					_.each(storeEvents[type],function(i,value){
						if(_.isFunction(value.handler)){
							if(value.type && value.el){
								argument.target = el;
								if(value.type === "nodelist" && _.contain(value.el,el)){
									value.handler(argument);
								}else if(value.el.isEqualNode && value.el.isEqualNode(el)){
									value.handler(argument);
								}
							}else{
								value.handler(argument);
							}
						}
					});
				}

			}
		}
	}();

	class Touch{
		constructor(selector){

		}
	}

})();
<commit_msg>*test<commit_after>(function(){
	"use strict";
	if(!window.ontouchstart){return;}
	const _=function(){
		let type=function(obj){
   			//'boolean', 'number', 'string', 'function', 'array', 'date', 'regexp', 'object', 'error'
			return obj == null ? String(obj) : {}.toString.call(obj).toLowerCase().replace(/\[object\s|\]/g, '')|| "object";
		},
		toArray=function(arr){
			if(!arr) return [];
			return [].slice.call(arr,0);
		},
		isString=function(str){
			return type(str)==="string";
		},
		isArray=Array.isArray||function(arr) {
			return type(arr) === 'array';
		},
		isFunction=function(value) {
			return type(value) === "function";
		},
		isObject=function(obj) {
			return type(obj) === "object";
		};
   		return {
   			type,
   			toArray,
   			isString,
   			isArray,
   			isFunction,
   			isObject,
   		};
	}();

	const each=function(obj,callback){
		let len=0,i=0;
		if(!obj){return;}
		if(_.isArray(obj)){
			for(len=obj.length;i<len;i++){
				let val=callback.call(obj[i],i,obj[i]);
				if(val===false) break;
			}
		}else if(_.isObject(obj)){
			for(i in obj){
				if(obj.hasOwnProperty(i)){
					let val=callback.call(obj[i],i,obj[i]);
					if(val===false) break;
				}
			}
		}else{
			throw Error("参数格式错误")
		}
	};

	const extend = function(obj) {
		each(slice.call(arguments,1), function(i,value) {
			for(let prop in value) {
				obj[prop] = value[prop];
			}
		});
		return obj;
    };

	//console.log(_.isArray([]),_.isObject({}),_.isFunction(function(){}),_.isString(""));

	extend(_,{
		/**
		 * 生成uuid
		 * @return {String} uuid
		 */
		uuid(){
			return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
				let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
				return v.toString(16);
			});
		},
		each,
		extend,
		/**
		 * 获取当前时间距1970/1/1时间戳
		 * @return {Number}	时间戳
		 */
		getTime:(){
			return +new Date();
		},
		/**
		 * 获取坐标点信息
		 * @param {Object} event 对象
		 * @return {Object}	坐标点信息
		 */
		getPosInfo(event){
			let _touches=event.touches;
			if(_touches||_touches.length===0){
				return;
			}
			return {
				pageX:event.touches[0].pageX,
				pageY:event.touches[0].pageY,
				clientX:event.touches[0].clientX||0,
				clientY:event.touches[0].clientY||0
			}
		},
		/**
		 * 获取划动方向
		 * @param {Number} sX 起始点x坐标
		 * @param {Number} sY 起始点y坐标
		 * @param {Number} eX 结束点x坐标
		 * @param {Number} eY 结束点y坐标
		 * @return {String}	direction 方向
		 */
		getDirection(sX,sY,eX,eY){
			let [xRes,xResAbs]=[sX-eX,Math.abs(sX-eX)];
			let [yRes,yResAbs]=[sY-eY,Math.abs(sY-eY)];
			let direction="";

			if(xResAbs>=yResAbs&&xResAbs>25){
				direction=(xRes>0)?"Right":"Left";
			}else if(yResAbs>xResAbs&&yResAbs>25){
				direction=(yRes>0?"Down":"Up")
			}
			return direction;
		},
		/**
		 * 获取两点之间距离
		 * @param {Number} sX 起始点x坐标
		 * @param {Number} sY 起始点y坐标
		 * @param {Number} eX 结束点x坐标
		 * @param {Number} eY 结束点y坐标
		 * @return {Number}
		 */
		getDistance:(sX,sY,eX,eY)=>Math.sqrt(Math.pow(sX-eX,2)+Math.pow(sY-eY,2)),
		/**
		 * 获取长度
		 * @param {Object} v 坐标点
		 * @return {Number}
		 */
		getLength:v=>Math.sqrt(v.x*v.x+v.y*v.y),
		/**
		 * 叉乘
		 * @param {Object} v1 坐标点
		 * @param {Object} v2 坐标点
		 * @return {Number}
		 */
		cross:(v1,v2)=>v1.x*v2.y-v1.y*v2.x,
		/**
		 * 取向量
		 * @param {Number} sX 起始点x坐标
		 * @param {Number} sY 起始点y坐标
		 * @param {Number} eX 结束点x坐标
		 * @param {Number} eY 结束点y坐标
		 * @return {Number}
		 */
		getVector:(sX,sY,eX,eY)=>sX*eX+sY*eY,
		/**
		 * 获取角度 a*b=|a|*|b|*cos(deg); a*b=x1*x2+y1*y2
		 * @param {Object} v1 坐标点
		 * @param {Object} v2 坐标点
		 * @return {Number} Math.acos(r);
		 *
		 */
		getAngle(v1,v2){
			let mr=this.getLength(v1)*this.getLength(v2);
			if(mr===0){return 0;}

			let r=this.getVector(v1.x,v1.y,v2.x,v2.y)/mr;
			if(v>1){
				r=1;
			}
			return Math.acos(r);
		},
		/**
		 * 获取旋转的角度
		 * @param {Object} v1 坐标点
		 * @param {Object} v2 坐标点
		 * @return {Number} 角度值
		 */
		getRotateAngle(v1,v2){
			let angle=this.getAngle(v1,v2);
			if(this.cross(v1,v2)>0){
				angle*=-1;
			}
			return angle*180/Math.PI;
		},

		/**
		 * 绑定事件
		 * @param {Element} el
		 * @param {String} type
		 * @param {Function} fn
		 */
		bind(el,type,fn){
			el.addEventListener ? el.addEventListener(type, fn, false) : el.attachEvent("on" + type, fn);
		},
		/**
		 * 解绑事件
		 * @param {Element} el
		 * @param {String} type
		 * @param {Function} fn
		 */
		unBind(el,type,fn){
			el.removeEventListener ? el.removeEventListener(type, fn, false) : el.detachEvent("on" + type, fn);
		},
		/**
		 * 事件对象
		 * @param {Object} event
		 * @param {Object} obj
		 * @return {Object} new Event
		 */
		wrapEvent(ev,obj){
			let res={
				touches:ev.touches,
				type:ev.type
			}
			if(this.isObject(obj)){
				res=this.extend(res,obj)
			}
			return res;
		},
		/**
		 * 元素A元素是否包含B元素
		 * @param {Element} A
		 * @param {Element} B
		 */
		contains:(A,B)=>A.contains(B)

	});

	var Event=function(){
		let storeEvents={};
		return{
			/**
			 * add an event handler
			 * @param {String} type
			 * @param {String|Function} el
			 * @param {Function} handler
			 */
			add(type,el,handler){
				let selector=el,
					len=arguments.length,
					finalObject={},
					_type;

				//Event.add("swipe",function(){});
				if(_.isString(el)){
					el=document.querySelectorAll(el);
				}
				if(len===2 && _.isFunction(el)){

					finalObject={
						//selector:"",
						//el:null,
						handler:el
					};

				}else if(len===3 && el instanceof HTMLElement || el instanceof NodeList && _.isFunction(handler)){
					//Event.add("swipe","#div",function(ev){})

					_type=_.type(el);

					finalObject={
						type:_type,
						selector,
						el:_type==="nodelist"?_.toArray(el):el,
						handler
					}

				}

				storeEvents[type]||(storeEvents[type]=[]);
				storeEvents[type].push(finalObject);
			},
			/**
			 * remove an event handle
			 * @param {Style} type
			 * @param {String|Function} selector
			 */
			remove(type,selector){
				let len=arguments.length;
				if(_.isString(type) && _.isArray(storeEvent[type]) && storeEvents[type].length){
					if(len===1){
						storeEvents[type]=[];
					}else if(len===2){
						storeEvents[type]=storeEvents[type].filter(item => !(item.selector===selector || !_.isString(selector) && item.selector.isEqualNode(selector)))
					}

				}
			},
			/**
			 * trigger an event handle
			 * @param {String} type
			 * @param {DocumentElement} el
			 * @param {type} argument
			 */
			trigger(type,el,argument){
				let len=arguments.length;

				//Event.trigger("swipe",document.querySelector("#div"),{...})
				if(len===3 && _.isArray(storeEvents[type]) && storeEvents[type].length){
					_.each(storeEvents[type],function(i,value){
						if(_.isFunction(value.handler)){
							if(value.type && value.el){
								argument.target = el;
								if(value.type === "nodelist" && _.contain(value.el,el)){
									value.handler(argument);
								}else if(value.el.isEqualNode && value.el.isEqualNode(el)){
									value.handler(argument);
								}
							}else{
								value.handler(argument);
							}
						}
					});
				}

			}
		}
	}();

	class Touch{
		constructor(selector){

		}
	}

})();
<|endoftext|>


<commit_before>#define COMMENT(str)
#comment COMMENT allows the definition of comments that are removed even when
#comment js comments are not stripped from the source code.

#ifdef HELMA
#comment Helma has its own dontEnum() method and does not need an emulation.
#undef DONT_ENUM
#endif // HELMA

#if (defined(SET_ITERATOR) || defined(BROWSER_LEGACY)) && defined(DONT_ENUM) && !defined(EXTEND_OBJECT)
#comment Setting functions on bind objects with using DONT_ENUM is only supported
#comment when EXTEND_OBJECT is activated. As otherwise dontEnum() cannot be used
#comment to hide the iterator method on objects not inheriting from Base (e.g. a
#comment simple object literal). So lets turn off DONT_ENUM.
#undef DONT_ENUM
#endif // (SET_ITERATOR || BROWSER_LEGACY) && DONT_ENUM && !EXTEND_OBJECT

#if defined(DONT_ENUM) || defined(HELMA)
#comment Define the HIDE parameter, to be added to extend() after the object
#comment that defines the fields to be injected, if dontEnum should be called
#comment for these fields. This only does something if dontEnum() is there.
#define HIDE _hide: true,
#else // !DONT_ENUM && !HELMA
#define HIDE
#endif // !DONT_ENUM && !HELMA

#comment When setting iterator functions without using dontEnum or when using
#comment the legacy workaround for Function#apply, we need to check the field
#comment names to see if they are to be hidden. Anything starting with __ is
#comment hidden, but only when not in DONT_ENUM mode!
#comment Also, we need to filter out prototype (and constructor in legacy mode)
#comment as these are emurated on some browsers.
#comment name.indexOf('__') != 0 is faster than name.substring(0, 2) != '__'
#if defined(BROWSER_LEGACY)
#comment Allways filter out __ fields on legacy browsers, as they are used both
#comment for emulating Function#apply/#call and for faking __proto__
#define AND_NAME_IS_VISIBLE(NAME) && NAME.indexOf('__') != 0 && NAME != 'constructor'
#elif defined(SET_ITERATOR)
#define AND_NAME_IS_VISIBLE(NAME) && NAME.indexOf('__') != 0
#else // !SET_ITERATOR && !BROWSER_LEGACY
#define AND_NAME_IS_VISIBLE(NAME)
#endif // !SET_ITERATOR && !BROWSER_LEGACY
<commit_msg>Changed __proto__ workaround to be activated by FIX_PROTO, so it can be turned of e.g. when on Rhino<commit_after>#define COMMENT(str)
#comment COMMENT allows the definition of comments that are removed even when
#comment js comments are not stripped from the source code.

#ifdef HELMA
#comment Helma has its own dontEnum() method and does not need an emulation.
#undef DONT_ENUM
#endif // HELMA

#if (defined(SET_ITERATOR) || defined(BROWSER_LEGACY)) && defined(DONT_ENUM) && !defined(EXTEND_OBJECT)
#comment Setting functions on bind objects with using DONT_ENUM is only supported
#comment when EXTEND_OBJECT is activated. As otherwise dontEnum() cannot be used
#comment to hide the iterator method on objects not inheriting from Base (e.g. a
#comment simple object literal). So lets turn off DONT_ENUM.
#undef DONT_ENUM
#endif // (SET_ITERATOR || BROWSER_LEGACY) && DONT_ENUM && !EXTEND_OBJECT

#if defined(DONT_ENUM) || defined(HELMA)
#comment Define the HIDE parameter, to be added to extend() after the object
#comment that defines the fields to be injected, if dontEnum should be called
#comment for these fields. This only does something if dontEnum() is there.
#define HIDE _hide: true,
#else // !DONT_ENUM && !HELMA
#define HIDE
#endif // !DONT_ENUM && !HELMA

#comment When setting iterator functions without using dontEnum or when using
#comment the legacy workaround for Function#apply, we need to check the field
#comment names to see if they are to be hidden. Anything starting with __ is
#comment hidden, but only when not in DONT_ENUM mode!
#comment Also, we need to filter out prototype (and constructor in legacy mode)
#comment as these are emurated on some browsers.
#comment name.indexOf('__') != 0 is faster than name.substring(0, 2) != '__'
#if defined(BROWSER_LEGACY)
#comment Allways filter out __ fields on legacy browsers, as they are used both
#comment for emulating Function#apply/#call and for faking __proto__
#define AND_NAME_IS_VISIBLE(NAME) && NAME.indexOf('__') != 0 && NAME != 'constructor'
#elif defined(SET_ITERATOR)
#define AND_NAME_IS_VISIBLE(NAME) && NAME.indexOf('__') != 0
#else // !SET_ITERATOR && !BROWSER_LEGACY
#define AND_NAME_IS_VISIBLE(NAME)
#endif // !SET_ITERATOR && !BROWSER_LEGACY

#comment It appears that __proto__ is broken on IE browsers, so we even need it
#comment for non legacy browsers:
#ifndef RHINO
#define FIX_PROTO
#endif // !RHINO<|endoftext|>