<commit_before>/*

hybrid.js - object/functional hybrid model

The MIT License (MIT)

Copyright (c) 2016 Dale Schumacher

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
"use strict";

var hybrid = module.exports;

var log = console.log;
//var log = function () {};

var crypto = require('crypto');

var deepFreeze = function deepFreeze(obj) {  // make object immutable
    if ((obj === null) || (typeof obj !== 'object')) {
        return obj;
    }
    var propNames = Object.getOwnPropertyNames(obj);
    propNames.forEach(function (name) {  // Freeze properties before freezing self
        deepFreeze(obj[name]);
    });
    return Object.freeze(obj);  // Freeze self (no-op if already frozen)
};

var generateAddress = function generateAddress() {  // generate unique actor address string
    return crypto.randomBytes(42).toString('base64');
};

var newborn = {};  // address -> behavior map for newborn actors
var actors = {};  // address -> behavior map for established actors

hybrid.create = function create(behavior) {  // add new actor to behavior result
    if (typeof behavior !== 'function') {
        behavior = undefined;
    }
    var address = generateAddress();
    newborn[address] = behavior;
    log('create:', address);
    return address;
};

hybrid.send = function send(address, message) {  // add new message-event to behavior result
    var event = {
        target: address,
        message: message
    };
    log('send:', event);
    return deepFreeze(event);
};

hybrid.apply = function apply(result) {  // apply effects from stand-alone result (no 'self')
    result.actors.forEach(function (address) {  // new actors created
        actors[address] = newborn[address];
    });
    newborn = {};  // clear nursery
    result.events.forEach(function (event) {  // new message-events
        setImmediate(hybrid.dispatch, event);
    });
};

hybrid.dispatch = function dispatch(event) {  // deliver message-event
    try {
        log('dispatch:', event);
        hybrid.self = event.target;  // begin transaction
        var behavior = actors[hybrid.self];  // Find the behavior associated with the actor address
        var result = behavior(event.message);  // Invoke the behavior with the message as a parameter
        log('dispatch.result:', result);
        hybrid.apply(result);
        if (typeof result.behavior === 'function') {  // optional replacement behavior
            actors[hybrid.self] = result.behavior;
        }
    } catch (error) {
        log('dispatch.error:', error);
    } finally {
        hybrid.self = undefined;  // end transaction
    }
};
<commit_msg>Protect actor behavior during replacement<commit_after>/*

hybrid.js - object/functional hybrid model

The MIT License (MIT)

Copyright (c) 2016 Dale Schumacher

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
"use strict";

var hybrid = module.exports;

var log = console.log;
//var log = function () {};

var crypto = require('crypto');

var deepFreeze = function deepFreeze(obj) {  // make object immutable
    if ((obj === null) || (typeof obj !== 'object')) {
        return obj;
    }
    var propNames = Object.getOwnPropertyNames(obj);
    propNames.forEach(function (name) {  // Freeze properties before freezing self
        deepFreeze(obj[name]);
    });
    return Object.freeze(obj);  // Freeze self (no-op if already frozen)
};

var generateAddress = function generateAddress() {  // generate unique actor address string
    return crypto.randomBytes(42).toString('base64');
};

var newborn = {};  // address -> behavior map for newborn actors
var actors = {};  // address -> behavior map for established actors

hybrid.create = function create(behavior) {  // add new actor to behavior result
    if (typeof behavior !== 'function') {
        behavior = undefined;
    }
    var address = generateAddress();
    newborn[address] = behavior;
    log('create:', address);
    return address;
};

hybrid.send = function send(address, message) {  // add new message-event to behavior result
    var event = {
        target: address,
        message: message
    };
    log('send:', event);
    return deepFreeze(event);
};

hybrid.apply = function apply(result) {  // apply effects from stand-alone result (no 'self')
    result.actors.forEach(function (address) {  // new actors created
        var beahvior = newborn[address];
        if (typeof behavior === 'function') {
            actors[address] = behavior;
        }
    });
    newborn = {};  // clear nursery
    result.events.forEach(function (event) {  // new message-events
        setImmediate(hybrid.dispatch, event);
    });
};

hybrid.dispatch = function dispatch(event) {  // deliver message-event
    try {
        log('dispatch:', event);
        hybrid.self = event.target;  // begin transaction
        var behavior = actors[hybrid.self];  // Find the behavior associated with the actor address
        var result = behavior(event.message);  // Invoke the behavior with the message as a parameter
        log('dispatch.result:', result);
        hybrid.apply(result);
        if (typeof result.behavior === 'function') {  // optional replacement behavior
            actors[hybrid.self] = result.behavior;
        }
    } catch (error) {
        log('dispatch.error:', error);
    } finally {
        hybrid.self = undefined;  // end transaction
    }
};
<|endoftext|>


<commit_before>"use strict";

module.exports = {
  hooks: {
    "pre-commit": "lint-staged"
  }
};
<commit_msg>style(husky config): update formatting<commit_after>"use strict";

module.exports = {
  hooks: {
    "pre-commit": "lint-staged",
  },
};
<|endoftext|>


<commit_before>var Task                = require('ember-cli/lib/models/task');
var ConfigurationReader = require('../../utilities/configuration-reader');
var Promise             = require('ember-cli/lib/ext/promise');
var SilentError         = require('ember-cli/lib/errors/silent');
var chalk               = require('chalk');
var fs                  = require('fs');
var path                = require('path');

var ncp   = Promise.denodeify(require('ncp'));
var white = chalk.white;
var green = chalk.green;

var AssetsUploader = require('../../utilities/assets-uploader');

var EXPIRE_IN_2030 = new Date('2030');
var TWO_YEAR_CACHE_PERIOD_IN_SEC = 60 * 60 * 24 * 365 * 2;

module.exports = Task.extend({
  run: function(options) {
    var broccoli  = require('broccoli');

    var config = new ConfigurationReader({
      environment: options.environment,
      configFile: options.deployConfigFile
    }).config;

    var fileTreeOrPath;
    if(config.get('assets.gzip') === false) {
      fileTreeOrPath = 'dist';
    } else {
      var gzipFiles = require('broccoli-gzip');

      fileTreeOrPath = gzipFiles('dist', {
        extensions: config.get('assets.gzipExtensions'),
        appendSuffix: false
      });
    }

    var builder = new broccoli.Builder(fileTreeOrPath);

    return builder.build()
      .then(this.processBuildResult.bind(this))
      .then(this.uploadAssets.bind(this, options.environment, options.deployConfigFile))
      .then(function() {
        builder.cleanup();
      });
  },

  uploadAssets: function(environment, configFile) {
    var config = new ConfigurationReader({
<<<<<<< HEAD
      environment: environment,
      configFile: configFile
    });
=======
      environment: environment
    }).config;
>>>>>>> Encapsulate defaults in a config model
    var assetsUploader = new AssetsUploader({
      ui: this.ui,
      config: config,
      type: config.get('assets.type'),
      project: this.project
    });

    return assetsUploader.upload();
  },

  processBuildResult: function(results) {
    return this.clearOutputPath('tmp/assets-sync/')
    .then(function() {
      return this.copyToOutputPath(results.directory, 'tmp/assets-sync/');
    }.bind(this))
  },

  clearOutputPath: function(outputPath) {
    var rimraf = Promise.denodeify(require('rimraf'));
    if (!fs.existsSync(outputPath)) { return Promise.resolve(); }

    var promises = [];
    var entries = fs.readdirSync(outputPath);

    for (var i = 0, l = entries.length; i < l; i++) {
      promises.push(rimraf(path.join(outputPath, entries[i])));
    }

    return Promise.all(promises);
  },

  copyToOutputPath: function(inputPath, outputPath) {
    var mkdirp = require('mkdirp');
    if (!fs.existsSync(outputPath)) {
      mkdirp.sync(outputPath);
    }

    return ncp(inputPath, outputPath, {
      dereference: true,
      clobber: true,
      stopOnErr: true,
      limit: 2
    });
  }
});
<commit_msg>Removed erroneous conflict markers.<commit_after>var Task                = require('ember-cli/lib/models/task');
var ConfigurationReader = require('../../utilities/configuration-reader');
var Promise             = require('ember-cli/lib/ext/promise');
var SilentError         = require('ember-cli/lib/errors/silent');
var chalk               = require('chalk');
var fs                  = require('fs');
var path                = require('path');

var ncp   = Promise.denodeify(require('ncp'));
var white = chalk.white;
var green = chalk.green;

var AssetsUploader = require('../../utilities/assets-uploader');

var EXPIRE_IN_2030 = new Date('2030');
var TWO_YEAR_CACHE_PERIOD_IN_SEC = 60 * 60 * 24 * 365 * 2;

module.exports = Task.extend({
  run: function(options) {
    var broccoli  = require('broccoli');

    var config = new ConfigurationReader({
      environment: options.environment,
      configFile: options.deployConfigFile
    }).config;

    var fileTreeOrPath;
    if(config.get('assets.gzip') === false) {
      fileTreeOrPath = 'dist';
    } else {
      var gzipFiles = require('broccoli-gzip');

      fileTreeOrPath = gzipFiles('dist', {
        extensions: config.get('assets.gzipExtensions'),
        appendSuffix: false
      });
    }

    var builder = new broccoli.Builder(fileTreeOrPath);

    return builder.build()
      .then(this.processBuildResult.bind(this))
      .then(this.uploadAssets.bind(this, options.environment, options.deployConfigFile))
      .then(function() {
        builder.cleanup();
      });
  },

  uploadAssets: function(environment, configFile) {
    var config = new ConfigurationReader({
      environment: environment,
      configFile: configFile
    }).config;

    var assetsUploader = new AssetsUploader({
      ui: this.ui,
      config: config,
      type: config.get('assets.type'),
      project: this.project
    });

    return assetsUploader.upload();
  },

  processBuildResult: function(results) {
    return this.clearOutputPath('tmp/assets-sync/')
    .then(function() {
      return this.copyToOutputPath(results.directory, 'tmp/assets-sync/');
    }.bind(this))
  },

  clearOutputPath: function(outputPath) {
    var rimraf = Promise.denodeify(require('rimraf'));
    if (!fs.existsSync(outputPath)) { return Promise.resolve(); }

    var promises = [];
    var entries = fs.readdirSync(outputPath);

    for (var i = 0, l = entries.length; i < l; i++) {
      promises.push(rimraf(path.join(outputPath, entries[i])));
    }

    return Promise.all(promises);
  },

  copyToOutputPath: function(inputPath, outputPath) {
    var mkdirp = require('mkdirp');
    if (!fs.existsSync(outputPath)) {
      mkdirp.sync(outputPath);
    }

    return ncp(inputPath, outputPath, {
      dereference: true,
      clobber: true,
      stopOnErr: true,
      limit: 2
    });
  }
});
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2012, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

/* This file was autogenerated from https://raw.github.com/dbp/sublime-rust/master/Rust.tmLanguage (uuid: ) */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var RustHighlightRules = function() {
    // regexp must not have capturing parentheses. Use (?:) instead.
    // regexps are ordered -> the first match is used

    this.$rules = { start:
       [ { token: 'variable.other.source.rust',
           regex: '\'[a-zA-Z_][a-zA-Z0-9_]*[^\\\']' },
         { token: 'string.quoted.single.source.rust',
           regex: '\'',
           push:
            [ { token: 'string.quoted.single.source.rust',
                regex: '\'',
                next: 'pop' },
              { include: '#rust_escaped_character' },
              { defaultToken: 'string.quoted.single.source.rust' } ] },
         {
            stateName: "bracketedComment",
            onMatch : function(value, currentState, stack){
                stack.unshift(this.next, value.length - 1, currentState);
                return "string.quoted.raw.source.rust";
            },
            regex : /r#*"/,
            next  : [
                {
                    onMatch : function(value, currentState, stack) {
                        var token = "string.quoted.raw.source.rust";
                        if (value.length >= stack[1]) {
                            if (value.length > stack[1])
                                token = "invalid";
                            stack.shift();
                            stack.shift();
                            this.next = stack.shift();
                        } else {
                            this.next = "";
                        }
                        return token;
                    },
                    regex : /"#*/,
                    next  : "start"
                }, {
                    defaultToken : "string.quoted.raw.source.rust"
                }
            ]
         },
         { token: 'string.quoted.double.source.rust',
           regex: '"',
           push:
            [ { token: 'string.quoted.double.source.rust',
                regex: '"',
                next: 'pop' },
              { include: '#rust_escaped_character' },
              { defaultToken: 'string.quoted.double.source.rust' } ] },
         { token: [ 'keyword.source.rust', 'meta.function.source.rust',
              'entity.name.function.source.rust', 'meta.function.source.rust' ],
           regex: '\\b(fn)(\\s+)([a-zA-Z_][a-zA-Z0-9_][\\w\\:,+ \\\'<>]*)(\\s*\\()' },
         { token: 'support.constant', regex: '\\b[a-zA-Z_][\\w\\d]*::' },
         { token: 'keyword.source.rust',
           regex: '\\b(?:as|assert|break|claim|const|copy|Copy|do|drop|else|extern|fail|for|if|impl|in|let|log|loop|match|mod|module|move|mut|Owned|priv|pub|pure|ref|return|unchecked|unsafe|use|while|mod|Send|static|trait|class|struct|enum|type)\\b' },
         { token: 'storage.type.source.rust',
           regex: '\\b(?:Self|m32|m64|m128|f80|f16|f128|int|uint|float|char|bool|u8|u16|u32|u64|f32|f64|i8|i16|i32|i64|str|option|either|c_float|c_double|c_void|FILE|fpos_t|DIR|dirent|c_char|c_schar|c_uchar|c_short|c_ushort|c_int|c_uint|c_long|c_ulong|size_t|ptrdiff_t|clock_t|time_t|c_longlong|c_ulonglong|intptr_t|uintptr_t|off_t|dev_t|ino_t|pid_t|mode_t|ssize_t)\\b' },
         { token: 'variable.language.source.rust', regex: '\\bself\\b' },
         { token: 'keyword.operator',
            regex: '!|\\$|\\*|\\-\\-|\\-|\\+\\+|\\+|-->|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|/=|%=|\\+=|\\-=|&=|\\^=|,|;' },
         { token: 'constant.language.source.rust',
           regex: '\\b(?:true|false|Some|None|Left|Right|Ok|Err)\\b' },
         { token: 'support.constant.source.rust',
           regex: '\\b(?:EXIT_FAILURE|EXIT_SUCCESS|RAND_MAX|EOF|SEEK_SET|SEEK_CUR|SEEK_END|_IOFBF|_IONBF|_IOLBF|BUFSIZ|FOPEN_MAX|FILENAME_MAX|L_tmpnam|TMP_MAX|O_RDONLY|O_WRONLY|O_RDWR|O_APPEND|O_CREAT|O_EXCL|O_TRUNC|S_IFIFO|S_IFCHR|S_IFBLK|S_IFDIR|S_IFREG|S_IFMT|S_IEXEC|S_IWRITE|S_IREAD|S_IRWXU|S_IXUSR|S_IWUSR|S_IRUSR|F_OK|R_OK|W_OK|X_OK|STDIN_FILENO|STDOUT_FILENO|STDERR_FILENO)\\b' },
         { token: 'meta.preprocessor.source.rust',
           regex: '\\b\\w\\(\\w\\)*!|#\\[[\\w=\\(\\)_]+\\]\\b' },
         { token: 'constant.numeric.integer.source.rust',
           regex: '\\b(?:[0-9][0-9_]*|[0-9][0-9_]*(?:u|u8|u16|u32|u64)|[0-9][0-9_]*(?:i|i8|i16|i32|i64))\\b' },
         { token: 'constant.numeric.hex.source.rust',
           regex: '\\b(?:0x[a-fA-F0-9_]+|0x[a-fA-F0-9_]+(?:u|u8|u16|u32|u64)|0x[a-fA-F0-9_]+(?:i|i8|i16|i32|i64))\\b' },
         { token: 'constant.numeric.binary.source.rust',
           regex: '\\b(?:0b[01_]+|0b[01_]+(?:u|u8|u16|u32|u64)|0b[01_]+(?:i|i8|i16|i32|i64))\\b' },
         { token: 'constant.numeric.float.source.rust',
           regex: '[0-9][0-9_]*(?:f32|f64|f)|[0-9][0-9_]*[eE][+-]=[0-9_]+|[0-9][0-9_]*[eE][+-]=[0-9_]+(?:f32|f64|f)|[0-9][0-9_]*\\.[0-9_]+|[0-9][0-9_]*\\.[0-9_]+(?:f32|f64|f)|[0-9][0-9_]*\\.[0-9_]+%[eE][+-]=[0-9_]+|[0-9][0-9_]*\\.[0-9_]+%[eE][+-]=[0-9_]+(?:f32|f64|f)' },
         { token: 'comment.line.documentation.source.rust',
           regex: '//!.*$',
           push_:
            [ { token: 'comment.line.documentation.source.rust',
                regex: '$',
                next: 'pop' },
              { defaultToken: 'comment.line.documentation.source.rust' } ] },
         { token: 'comment.line.double-dash.source.rust',
           regex: '//.*$',
           push_:
            [ { token: 'comment.line.double-dash.source.rust',
                regex: '$',
                next: 'pop' },
              { defaultToken: 'comment.line.double-dash.source.rust' } ] },
         { token: 'comment.start.block.source.rust',
           regex: '/\\*',
           stateName: 'comment',
           push:
            [ { token: 'comment.start.block.source.rust',
                regex: '/\\*',
                push: 'comment' },
              { token: 'comment.end.block.source.rust',
                regex: '\\*/',
                next: 'pop' },
              { defaultToken: 'comment.block.source.rust' } ] } ],
      '#rust_escaped_character':
       [ { token: 'constant.character.escape.source.rust',
           regex: '\\\\(?:x[\\da-fA-F]{2}|[0-2][0-7]{,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.)' } ] }

    this.normalizeRules();
};

RustHighlightRules.metaData = { fileTypes: [ 'rs', 'rc' ],
      foldingStartMarker: '^.*\\bfn\\s*(\\w+\\s*)?\\([^\\)]*\\)(\\s*\\{[^\\}]*)?\\s*$',
      foldingStopMarker: '^\\s*\\}',
      name: 'Rust',
      scopeName: 'source.rust' }

oop.inherits(RustHighlightRules, TextHighlightRules);

exports.RustHighlightRules = RustHighlightRules;
});<commit_msg>Add highlight support for isize, usize, us and is<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2012, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

/* This file was autogenerated from https://raw.github.com/dbp/sublime-rust/master/Rust.tmLanguage (uuid: ) */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var RustHighlightRules = function() {
    // regexp must not have capturing parentheses. Use (?:) instead.
    // regexps are ordered -> the first match is used

    this.$rules = { start:
       [ { token: 'variable.other.source.rust',
           regex: '\'[a-zA-Z_][a-zA-Z0-9_]*[^\\\']' },
         { token: 'string.quoted.single.source.rust',
           regex: '\'',
           push:
            [ { token: 'string.quoted.single.source.rust',
                regex: '\'',
                next: 'pop' },
              { include: '#rust_escaped_character' },
              { defaultToken: 'string.quoted.single.source.rust' } ] },
         {
            stateName: "bracketedComment",
            onMatch : function(value, currentState, stack){
                stack.unshift(this.next, value.length - 1, currentState);
                return "string.quoted.raw.source.rust";
            },
            regex : /r#*"/,
            next  : [
                {
                    onMatch : function(value, currentState, stack) {
                        var token = "string.quoted.raw.source.rust";
                        if (value.length >= stack[1]) {
                            if (value.length > stack[1])
                                token = "invalid";
                            stack.shift();
                            stack.shift();
                            this.next = stack.shift();
                        } else {
                            this.next = "";
                        }
                        return token;
                    },
                    regex : /"#*/,
                    next  : "start"
                }, {
                    defaultToken : "string.quoted.raw.source.rust"
                }
            ]
         },
         { token: 'string.quoted.double.source.rust',
           regex: '"',
           push:
            [ { token: 'string.quoted.double.source.rust',
                regex: '"',
                next: 'pop' },
              { include: '#rust_escaped_character' },
              { defaultToken: 'string.quoted.double.source.rust' } ] },
         { token: [ 'keyword.source.rust', 'meta.function.source.rust',
              'entity.name.function.source.rust', 'meta.function.source.rust' ],
           regex: '\\b(fn)(\\s+)([a-zA-Z_][a-zA-Z0-9_][\\w\\:,+ \\\'<>]*)(\\s*\\()' },
         { token: 'support.constant', regex: '\\b[a-zA-Z_][\\w\\d]*::' },
         { token: 'keyword.source.rust',
           regex: '\\b(?:as|assert|break|claim|const|copy|Copy|do|drop|else|extern|fail|for|if|impl|in|let|log|loop|match|mod|module|move|mut|Owned|priv|pub|pure|ref|return|unchecked|unsafe|use|while|mod|Send|static|trait|class|struct|enum|type)\\b' },
         { token: 'storage.type.source.rust',
           regex: '\\b(?:Self|m32|m64|m128|f80|f16|f128|int|uint|isize|usize|float|char|bool|u8|u16|u32|u64|f32|f64|i8|i16|i32|i64|str|option|either|c_float|c_double|c_void|FILE|fpos_t|DIR|dirent|c_char|c_schar|c_uchar|c_short|c_ushort|c_int|c_uint|c_long|c_ulong|size_t|ptrdiff_t|clock_t|time_t|c_longlong|c_ulonglong|intptr_t|uintptr_t|off_t|dev_t|ino_t|pid_t|mode_t|ssize_t)\\b' },
         { token: 'variable.language.source.rust', regex: '\\bself\\b' },
         { token: 'keyword.operator',
            regex: '!|\\$|\\*|\\-\\-|\\-|\\+\\+|\\+|-->|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|/=|%=|\\+=|\\-=|&=|\\^=|,|;' },
         { token: 'constant.language.source.rust',
           regex: '\\b(?:true|false|Some|None|Left|Right|Ok|Err)\\b' },
         { token: 'support.constant.source.rust',
           regex: '\\b(?:EXIT_FAILURE|EXIT_SUCCESS|RAND_MAX|EOF|SEEK_SET|SEEK_CUR|SEEK_END|_IOFBF|_IONBF|_IOLBF|BUFSIZ|FOPEN_MAX|FILENAME_MAX|L_tmpnam|TMP_MAX|O_RDONLY|O_WRONLY|O_RDWR|O_APPEND|O_CREAT|O_EXCL|O_TRUNC|S_IFIFO|S_IFCHR|S_IFBLK|S_IFDIR|S_IFREG|S_IFMT|S_IEXEC|S_IWRITE|S_IREAD|S_IRWXU|S_IXUSR|S_IWUSR|S_IRUSR|F_OK|R_OK|W_OK|X_OK|STDIN_FILENO|STDOUT_FILENO|STDERR_FILENO)\\b' },
         { token: 'meta.preprocessor.source.rust',
           regex: '\\b\\w\\(\\w\\)*!|#\\[[\\w=\\(\\)_]+\\]\\b' },
         { token: 'constant.numeric.integer.source.rust',
           regex: '\\b(?:[0-9][0-9_]*|[0-9][0-9_]*(?:u|us|u8|u16|u32|u64)|[0-9][0-9_]*(?:i|is|i8|i16|i32|i64))\\b' },
         { token: 'constant.numeric.hex.source.rust',
           regex: '\\b(?:0x[a-fA-F0-9_]+|0x[a-fA-F0-9_]+(?:u|us|u8|u16|u32|u64)|0x[a-fA-F0-9_]+(?:i|is|i8|i16|i32|i64))\\b' },
         { token: 'constant.numeric.binary.source.rust',
           regex: '\\b(?:0b[01_]+|0b[01_]+(?:u|us|u8|u16|u32|u64)|0b[01_]+(?:i|is|i8|i16|i32|i64))\\b' },
         { token: 'constant.numeric.float.source.rust',
           regex: '[0-9][0-9_]*(?:f32|f64|f)|[0-9][0-9_]*[eE][+-]=[0-9_]+|[0-9][0-9_]*[eE][+-]=[0-9_]+(?:f32|f64|f)|[0-9][0-9_]*\\.[0-9_]+|[0-9][0-9_]*\\.[0-9_]+(?:f32|f64|f)|[0-9][0-9_]*\\.[0-9_]+%[eE][+-]=[0-9_]+|[0-9][0-9_]*\\.[0-9_]+%[eE][+-]=[0-9_]+(?:f32|f64|f)' },
         { token: 'comment.line.documentation.source.rust',
           regex: '//!.*$',
           push_:
            [ { token: 'comment.line.documentation.source.rust',
                regex: '$',
                next: 'pop' },
              { defaultToken: 'comment.line.documentation.source.rust' } ] },
         { token: 'comment.line.double-dash.source.rust',
           regex: '//.*$',
           push_:
            [ { token: 'comment.line.double-dash.source.rust',
                regex: '$',
                next: 'pop' },
              { defaultToken: 'comment.line.double-dash.source.rust' } ] },
         { token: 'comment.start.block.source.rust',
           regex: '/\\*',
           stateName: 'comment',
           push:
            [ { token: 'comment.start.block.source.rust',
                regex: '/\\*',
                push: 'comment' },
              { token: 'comment.end.block.source.rust',
                regex: '\\*/',
                next: 'pop' },
              { defaultToken: 'comment.block.source.rust' } ] } ],
      '#rust_escaped_character':
       [ { token: 'constant.character.escape.source.rust',
           regex: '\\\\(?:x[\\da-fA-F]{2}|[0-2][0-7]{,2}|3[0-6][0-7]?|37[0-7]?|[4-7][0-7]?|.)' } ] }

    this.normalizeRules();
};

RustHighlightRules.metaData = { fileTypes: [ 'rs', 'rc' ],
      foldingStartMarker: '^.*\\bfn\\s*(\\w+\\s*)?\\([^\\)]*\\)(\\s*\\{[^\\}]*)?\\s*$',
      foldingStopMarker: '^\\s*\\}',
      name: 'Rust',
      scopeName: 'source.rust' }

oop.inherits(RustHighlightRules, TextHighlightRules);

exports.RustHighlightRules = RustHighlightRules;
});<|endoftext|>


<commit_before>'use strict';

module.exports = class extends think.middleware.base {
  run(){
    var ips = this.config('deny_ip');
  }
}

module.exports = think.middleware({
  options: {
    //deny ip list
    deny_ip: []
  },
  run: function(){
    if (this.options.deny_ip.length === 0) {
      return true;
    }
    var clientIps = this.http.ip().split('.');
    var flag = this.options.deny_ip.some(function(item){
      return item.split('.').every(function(num, i){
        if (num === '*' || num === clientIps[i]) {
          return true;
        }
      });
    });
    if (flag) {
      this.http.res.statusCode = 403;
      this.http.end();
      return think.defer().promise;
    }
    return true;
  }
});
<commit_msg>rewrite deny ip middleware<commit_after>'use strict';
/**
 * deny ip access
 * @type {}
 */
module.exports = class extends think.middleware.base {
  async run(){
    let ips = this.config('deny_ip');
    if(think.isFunction(ips)){
      ips = await think.co.wrap(ips)(this.http);
    }
    if (!ips || think.isArray(ips) && ips.length === 0) {
      return true;
    }
    let sections = this.http.ip().split('.');
    let flag = ips.some((item) => {
      return item.split('.').every((num, i) => {
        if (num === '*' || num === sections[i]) {
          return true;
        }
      });
    });
    if (flag) {
      this.http.res.statusCode = 403;
      this.http.end();
      //return pedding promise to prevent next process
      return think.defer().promise;
    }
  }
}<|endoftext|>


<commit_before>const Pagetest = require('./Pagetest');
const credentials = require('./credentials');

exports.call = function (db, data, req) {
    const API = new Pagetest.API(credentials.wpt_dns, credentials.wpt_api_key);
    const testUrl = data.url;
    const testLocation = data.location;
    const isClone = data.isClone == 'true';
    const caching = data.caching == 'true';

    const testOptions = {
        connectivity: 'Native',
        location: testLocation,
        firstViewOnly: !caching,
        runs: 1,
        video: true,
        disableOptimization: true,
        pageSpeed: false,
        requests: false,
        breakDown: false,
        domains: false,
        saveResponseBodies: false,
        tcpDump: false,
        timeline: false,
        priority: 0,
        chromeTrace: false,
        netLog: false,
        disableHTTPHeaders: true,
        disableScreenshot: true,
        jpegQuality: 100,
        pingback: 'https://makefast.app.baqend.com/v1/code/testPingback'
    };

    const prewarmOptions = Object.assign({}, testOptions, {pingback: '', firstViewOnly: true});

    // test cloned website
    if (isClone) {
        const prewarmScript = `logData\t0\nnavigate\t${testUrl}`;

        const makefastUrl = testUrl.substr(0, testUrl.indexOf('?'));
        const testScript =
`setActivityTimeout\t150
logData\t0
navigate\t${testUrl}&noCaching=true&blockExternal=true
navigate\tabout:blank
logData\t1
navigate\t${testUrl}`;

        return API.runTest(prewarmScript, prewarmOptions).then(() => {
            return API.runTest(testScript, testOptions);
        }).then(result => {
            db.log.info(`Clone test, id: ${result.data.testId} script:\n${testScript}`);
            return {testId: result.data.testId};
        });
    }

    // test original website
    const testScript = `setActivityTimeout\t150\nnavigate\t${testUrl}`;
    return API.runTest(testScript, testOptions).then(result => {
        db.log.info(`Original test, id: ${result.data.testId} script:\n${testScript}`);
        return {testId: result.data.testId};
    });
};<commit_msg>updated timeouts<commit_after>const Pagetest = require('./Pagetest');
const credentials = require('./credentials');
const activityTimeout = 50;
const timeout = 30;

exports.call = function (db, data, req) {
    const API = new Pagetest.API(credentials.wpt_dns, credentials.wpt_api_key);
    const testUrl = data.url;
    const testLocation = data.location;
    const isClone = data.isClone == 'true';
    const caching = data.caching == 'true';

    const testOptions = {
        connectivity: 'Native',
        location: testLocation,
        firstViewOnly: !caching,
        runs: 1,
        video: true,
        disableOptimization: true,
        pageSpeed: false,
        requests: false,
        breakDown: false,
        domains: false,
        saveResponseBodies: false,
        tcpDump: false,
        timeline: true, //TODO: only for debugging
        priority: 0,
        chromeTrace: false,
        netLog: false,
        disableHTTPHeaders: true,
        disableScreenshot: true,
        jpegQuality: 100,
        poll: 1, //poll every second
        timeout: 2 * timeout, //set timeout
        pingback: 'https://makefast.app.baqend.com/v1/code/testPingback'
    };

    const prewarmOptions = Object.assign({}, testOptions, {pingback: '', firstViewOnly: true});

    // test cloned website
    if (isClone) {
        const prewarmScript = `logData\t0\nnavigate\t${testUrl}`;

        const makefastUrl = testUrl.substr(0, testUrl.indexOf('?'));

        //only pre-install SW, if we are interested in the first view
        const installSW = caching ? "" : `logData\t0
setTimeout\t${timeout}
navigate\t${testUrl}&noCaching=true&blockExternal=true
navigate\tabout:blank
logData\t1`

        const testScript =
            `setActivityTimeout\t${activityTimeout}
${installSW}
setTimeout\t${timeout}
navigate\t${testUrl}`;

        return API.runTest(prewarmScript, prewarmOptions).then(() => {
            return API.runTest(testScript, testOptions);
        }).then(result => {
            db.log.info(`Clone test, id: ${result.data.testId} script:\n${testScript}`);
            return {testId: result.data.testId};
        });
    }

    // test original website
    const testScript = `setActivityTimeout\t${activityTimeout}\nsetTimeout\t${timeout}\nnavigate\t${testUrl}`;
    return API.runTest(testScript, testOptions).then(result => {
        db.log.info(`Original test, id: ${result.data.testId} script:\n${testScript}`);
        return {testId: result.data.testId};
    });
};<|endoftext|>


<commit_before>'use strict'

const patchUrl = require('url-patch');
const http = require('http');

const parseJob = (query) => {
  const prefix = '/';
  if(query.startsWith(prefix)) {
    query = query.substring(prefix.length, query.length);
  }

  return objectifyJob(query);
};

const parseUrl = (job) => {
  return job.substring(0, job.lastIndexOf('/job/'));
};

const parseName = (job) => {
  return job.substring(job.lastIndexOf('/job/') + 5, job.length);
};

const objectifyJob = (job) => {
  const objectified = {
    url: job,
    patchedUrl: patchUrl(parseUrl(job)),
    name: parseName(job)
  };
  return objectified;
};

const getJob = (job, cb) => {
  const tree = 'tree=color,displayName,url,lastBuild[displayName,number,url,building,estimatedDuration,duration,timestamp,culprits[fullName]]';
  const jobInfo = {
    job: undefined,
    url: job.url
  };

  http.get(`${job.patchedUrl}/job/${job.name}/api/json?${tree}`, (res) => {
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
      jobInfo.job = JSON.parse(chunk);
    });
    res.on('end', () => {
      cb(null, jobInfo);
    });
  }).on('error', (e) => {
    cb(e, jobInfo);
  });
};

module.exports = (req, res, next) => {
  const job = parseJob(req.url);
  getJob(job, (err, results) => {
    if(err) {
      next(err);
    } else {
      res.send(JSON.stringify(results));
      next();
    }
  });
};
<commit_msg>catch JSON parse errors<commit_after>'use strict'

const patchUrl = require('url-patch');
const http = require('http');

const parseJob = (query) => {
  const prefix = '/';
  if(query.startsWith(prefix)) {
    query = query.substring(prefix.length, query.length);
  }

  return objectifyJob(query);
};

const parseUrl = (job) => {
  return job.substring(0, job.lastIndexOf('/job/'));
};

const parseName = (job) => {
  return job.substring(job.lastIndexOf('/job/') + 5, job.length);
};

const objectifyJob = (job) => {
  const objectified = {
    url: job,
    patchedUrl: patchUrl(parseUrl(job)),
    name: parseName(job)
  };
  return objectified;
};

const getJob = (job, cb) => {
  const tree = 'tree=color,displayName,url,lastBuild[displayName,number,url,building,estimatedDuration,duration,timestamp,culprits[fullName]]';
  const jobInfo = {
    job: undefined,
    url: job.url
  };

  http.get(`${job.patchedUrl}/job/${job.name}/api/json?${tree}`, (res) => {
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
      try {
        jobInfo.job = JSON.parse(chunk);
      } catch (SyntaxError) {
        cb(new Error(`failed to parse JSON: ${job}: ${chunk}`), null);
      }
    });
    res.on('end', () => {
      cb(null, jobInfo);
    });
  }).on('error', (e) => {
    cb(e, jobInfo);
  });
};

module.exports = (req, res, next) => {
  const job = parseJob(req.url);
  getJob(job, (err, results) => {
    if(err) {
      next(err);
    } else {
      res.send(JSON.stringify(results));
      next();
    }
  });
};
<|endoftext|>


<commit_before>/**
 *
 */
'use strict';

var distributeTranscludeDirective = function() {
  return {
    restrict: 'A',
    scope: false,
    transclude: true,
    link: function(scope, elem, attr, ctrl, transclude) {
      transclude(scope, function(clone) {
        var transcludeSelectors = elem[0].querySelectorAll('[content-select]');
        angular.forEach(clone, function(cloneEl) {
          var found = false;
          for (var i = transcludeSelectors.length; i--;) {
            var transcludeToElement = transcludeSelectors[i];
            if (isAllowedNode(cloneEl) && matches(cloneEl, transcludeToElement.attributes['content-select'])) {
              if (transcludeToElement.attributes['content-replace']) {
                if (transcludeToElement.parentNode) {
                  transcludeToElement.parentNode.replaceChild(cloneEl, transcludeToElement);
                } else {
                  console.error('Can\'t find parentNode!');
                }
              } else {
                transcludeToElement.appendChild(cloneEl);
              }

              found = true;
            }
          }

          if (!found) {
            cloneEl.remove();
          }
        });
      });
    },

    controller: function() {},
  };

  function isAllowedNode(node) {
    var nodeType = node.nodeType;
    return nodeType === 1 || nodeType === 9;
  }

  function matches(element, selector) {
    if (element.matches) {
      return element.matches(selector.value);
    } else if (element.matchesSelector) {
      return element.matchesSelector(selector.value);
    } else if (element.querySelectorAll) {
      return supportOlderBrowser(element, selector.value);
    } else {
      console.error('This browser doesn\'t support selector matches -> https://developer.mozilla.org/en-US/docs/Web/API/Element/matches');
    }

    return false;
  }

  function supportOlderBrowser(element, selector) {
    var matches = (element.document || element.ownerDocument).querySelectorAll(selector);
    var i = 0;

    while (matches[i] && matches[i] !== element) {
      i++;
    }

    return matches[i] ? true : false;
  }
};

var tfiwmModule = angular.module('tfiwm.distributetransclude', []);
tfiwmModule.directive('distributeTransclude', distributeTranscludeDirective);
<commit_msg>move the link function to the prelink function<commit_after>/**
 *
 */
'use strict';

var distributeTranscludeDirective = function() {
  return {
    restrict: 'A',
    scope: false,
    transclude: true,
    link: {
      pre: function(scope, elem, attr, ctrl, transclude) {
          transclude(scope, function(clone) {
            var transcludeSelectors = elem[0].querySelectorAll('[content-select]');
            angular.forEach(clone, function(cloneEl) {
              var found = false;
              for (var i = transcludeSelectors.length; i--;) {
                var transcludeToElement = transcludeSelectors[i];
                if (isAllowedNode(cloneEl) && matches(cloneEl, transcludeToElement.attributes['content-select'])) {
                  if (transcludeToElement.attributes['content-replace']) {
                    if (transcludeToElement.parentNode) {
                      transcludeToElement.parentNode.replaceChild(cloneEl, transcludeToElement);
                    } else {
                      console.error('Can\'t find parentNode!');
                    }
                  } else {
                    transcludeToElement.appendChild(cloneEl);
                  }

                  found = true;
                }
              }

              if (!found) {
                cloneEl.remove();
              }
            });
          });
        },
    },

    controller: function() {},
  };

  function isAllowedNode(node) {
    var nodeType = node.nodeType;
    return nodeType === 1 || nodeType === 9;
  }

  function matches(element, selector) {
    if (element.matches) {
      return element.matches(selector.value);
    } else if (element.matchesSelector) {
      return element.matchesSelector(selector.value);
    } else if (element.querySelectorAll) {
      return supportOlderBrowser(element, selector.value);
    } else {
      console.error('This browser doesn\'t support selector matches -> https://developer.mozilla.org/en-US/docs/Web/API/Element/matches');
    }

    return false;
  }

  function supportOlderBrowser(element, selector) {
    var matches = (element.document || element.ownerDocument).querySelectorAll(selector);
    var i = 0;

    while (matches[i] && matches[i] !== element) {
      i++;
    }

    return matches[i] ? true : false;
  }
};

var tfiwmModule = angular.module('tfiwm.distributetransclude', []);
tfiwmModule.directive('distributeTransclude', distributeTranscludeDirective);
<|endoftext|>


<commit_before>module.exports = function($, gulp, paths){

  return {
    /**
     * @name             dev
     * @description      Set the node environment to development
     *                   Require the ./src/server in order to run the server
     * @return {Stream}
     */
    dev: function(){
      $.nodemon({
        script: paths.server.root + '/index.js',
        env: { NODE_ENV: 'development' },
        /**
         * Nodemon watches all files from the directory it executes, in this
         * case the root directory. Must manually ignore all the non-server
         * files in order to prevent server reload on the file changes that
         * don't affect the server.
         */
        ignore: [
          'build/**/*',
          'coverage/**/*',
          'lib/**/*',
          'logs/**/*',
          'node_modules/**/*',
          'src/client/**/*',
          'src/spec/**/*'
        ]
      });
    },
    /**
     * @name             stage
     * @description      Set the node environment to stage
     *                   Require the ./src/server in order to run the server
     * @return {Stream}
     */
    stage: function(){
      $.nodemon({
        script: paths.server.root + '/index.js',
        env: { NODE_ENV: 'development' },
        /**
         * Nodemon watches all files from the directory it executes, in this
         * case the root directory. Must manually ignore all the non-server
         * files in order to prevent server reload on the file changes that
         * don't affect the server.
         */
        ignore: [
          'build/**/*',
          'coverage/**/*',
          'lib/**/*',
          'logs/**/*',
          'node_modules/**/*',
          'src/client/**/*',
          'src/spec/**/*'
        ]
      });
    }
  };
};
<commit_msg>enable user to pass in node environment<commit_after>module.exports = function($, gulp, paths){

  return {
    /**
     * @name             dev
     * @description      Set the node environment to development
     *                   Require the ./src/server in order to run the server
     * @return {Stream}
     */
    dev: function() {
      var env = process.env.NODE_ENV || 'development';

      $.nodemon({
        script: paths.server.root + '/index.js',
        env: { NODE_ENV: env },
        /**
         * Nodemon watches all files from the directory it executes, in this
         * case the root directory. Must manually ignore all the non-server
         * files in order to prevent server reload on the file changes that
         * don't affect the server.
         */
        ignore: [
          'build/**/*',
          'coverage/**/*',
          'lib/**/*',
          'logs/**/*',
          'node_modules/**/*',
          'src/client/**/*',
          'src/spec/**/*'
        ]
      });
    },
    /**
     * @name             stage
     * @description      Set the node environment to stage
     *                   Require the ./src/server in order to run the server
     * @return {Stream}
     */
    stage: function() {
      var env = process.env.NODE_ENV || 'development';
      $.nodemon({
        script: paths.server.root + '/index.js',
        env: { NODE_ENV: env },
        /**
         * Nodemon watches all files from the directory it executes, in this
         * case the root directory. Must manually ignore all the non-server
         * files in order to prevent server reload on the file changes that
         * don't affect the server.
         */
        ignore: [
          'build/**/*',
          'coverage/**/*',
          'lib/**/*',
          'logs/**/*',
          'node_modules/**/*',
          'src/client/**/*',
          'src/spec/**/*'
        ]
      });
    }
  };
};
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

(function (aGlobal) {
  var Cc = Components.classes;
  var Ci  =Components.interfaces;

  var ConsoleService = Cc['@mozilla.org/consoleservice;1']
                         .getService(Ci.nsIConsoleService);

  var DeleteOnlyEmptyFolder = {
    debug: true,

    log: function(aMessage) {
      if (!this.debug)
        return;

     ConsoleService.logStringMessage('[delete-only-empty-folder] '+aMessage);
    },

    getTargetFolder: function(aFolder) {
      var folders = aFolder ? [aFolder] : gFolderTreeView.getSelectedFolders();
      return folders[0];
    },

    isEmpty: function(aFolder) {
      return !aFolder.hasSubFolders && aFolder.getTotalMessages(false) === 0;
    },

    init: function() {
      gFolderTreeController.__delete_only_empty_folder__deleteFolder = gFolderTreeController.deleteFolder;
      gFolderTreeController.deleteFolder = function(aFolder, ...aArgs) {
        aFolder = DeleteOnlyEmptyFolder.getTargetFolder(aFolder);
        if (!DeleteOnlyEmptyFolder.isEmpty(aFolder)) {
          DeleteOnlyEmptyFolder.log('Cancel to delete folder: it is not empty folder.');
          return;
        }
        return gFolderTreeController.__delete_only_empty_folder__deleteFolder.apply(this, [aFolder].concat(aArgs));
      };

      window.__delete_only_empty_folder__CanDeleteFolder = window.CanDeleteFolder;
      window.CanDeleteFolder = function(aFolder, ...aArgs) {
        if (!DeleteOnlyEmptyFolder.isEmpty(aFolder)) {
          DeleteOnlyEmptyFolder.log('Disallow to delete non-empty folder.');
          return false;
        }
        return window.__delete_only_empty_folder__CanDeleteFolder.apply(this, [aFolder].concat(aArgs));
      };

      window.__delete_only_empty_folder__EnableMenuItem = window.EnableMenuItem;
      window.EnableMenuItem = function(aId, ...aArgs) {
        if (aId === 'folderPaneContext-remove') {
          let folders = gFolderTreeView.getSelectedFolders();
          if (!folders.every(DeleteOnlyEmptyFolder.isEmpty, DeleteOnlyEmptyFolder)) {
            DeleteOnlyEmptyFolder.log('Disallow to delete non-empty folder.');
            document.getElementById(aId).disabled = true;
            return;
          }
        }
        return window.__delete_only_empty_folder__EnableMenuItem.apply(this, [aId].concat(aArgs));
      };

      gFolderTreeView.__delete_only_empty_folder__canDrop = gFolderTreeView.canDrop;
      gFolderTreeView.canDrop = function(aRow, aOrientation, ...aArgs) {
        var dropTargetFolder = gFolderTreeView._rowMap[aRow]._folder;
        if (dropTargetFolder &&
            aOrientation === Ci.nsITreeView.DROP_ON) {
          let dt = this._currentTransfer;
          let types = dt.mozTypesAt(0);
          if (Array.indexOf(types, 'text/x-moz-folder') > -1) {
            for (let i = 0, maxi = dt.mozItemCount; i < maxi; i++) {
              let folder = dt.mozGetDataAt('text/x-moz-folder', i)
                             .QueryInterface(Ci.nsIMsgFolder);
              if (!DeleteOnlyEmptyFolder.isEmpty(folder)) {
                DeleteOnlyEmptyFolder.log('Dropped folder '+i+' is not empty..');
                return false;
              }
            }
          }
        }
        return gFolderTreeView.__delete_only_empty_folder__canDrop.apply(this, [aRow, aOrientation].concat(aArgs));
      };
    }
  };

  document.addEventListener('DOMContentLoaded', function onDOMContentLoaded(aEvent) {
    document.removeEventListener('DOMContentLoaded', onDOMContentLoaded);
    DeleteOnlyEmptyFolder.init();
  });

  aGlobal.DeleteOnlyEmptyFolder = DeleteOnlyEmptyFolder;
})(this);
<commit_msg>Disallow to dlop non-empty folder only onto a trash folder<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

(function (aGlobal) {
  var Cc = Components.classes;
  var Ci  =Components.interfaces;

  var ConsoleService = Cc['@mozilla.org/consoleservice;1']
                         .getService(Ci.nsIConsoleService);

  var DeleteOnlyEmptyFolder = {
    debug: true,

    log: function(aMessage) {
      if (!this.debug)
        return;

     ConsoleService.logStringMessage('[delete-only-empty-folder] '+aMessage);
    },

    getTargetFolder: function(aFolder) {
      var folders = aFolder ? [aFolder] : gFolderTreeView.getSelectedFolders();
      return folders[0];
    },

    isEmpty: function(aFolder) {
      return !aFolder.hasSubFolders && aFolder.getTotalMessages(false) === 0;
    },

    isInTrash: function(aFolder) {
      if (!aFolder)
        return false;

      if (aFolder.flags & Ci.nsMsgFolderFlags.Trash)
        return true;

      return this.isInTrash(aFolder.parent);
    },

    init: function() {
      gFolderTreeController.__delete_only_empty_folder__deleteFolder = gFolderTreeController.deleteFolder;
      gFolderTreeController.deleteFolder = function(aFolder, ...aArgs) {
        aFolder = DeleteOnlyEmptyFolder.getTargetFolder(aFolder);
        if (!DeleteOnlyEmptyFolder.isEmpty(aFolder)) {
          DeleteOnlyEmptyFolder.log('Cancel to delete folder: it is not empty folder.');
          return;
        }
        return gFolderTreeController.__delete_only_empty_folder__deleteFolder.apply(this, [aFolder].concat(aArgs));
      };

      window.__delete_only_empty_folder__CanDeleteFolder = window.CanDeleteFolder;
      window.CanDeleteFolder = function(aFolder, ...aArgs) {
        if (!DeleteOnlyEmptyFolder.isEmpty(aFolder)) {
          DeleteOnlyEmptyFolder.log('Disallow to delete non-empty folder.');
          return false;
        }
        return window.__delete_only_empty_folder__CanDeleteFolder.apply(this, [aFolder].concat(aArgs));
      };

      window.__delete_only_empty_folder__EnableMenuItem = window.EnableMenuItem;
      window.EnableMenuItem = function(aId, ...aArgs) {
        if (aId === 'folderPaneContext-remove') {
          let folders = gFolderTreeView.getSelectedFolders();
          if (!folders.every(DeleteOnlyEmptyFolder.isEmpty, DeleteOnlyEmptyFolder)) {
            DeleteOnlyEmptyFolder.log('Disallow to delete non-empty folder.');
            document.getElementById(aId).disabled = true;
            return;
          }
        }
        return window.__delete_only_empty_folder__EnableMenuItem.apply(this, [aId].concat(aArgs));
      };

      gFolderTreeView.__delete_only_empty_folder__canDrop = gFolderTreeView.canDrop;
      gFolderTreeView.canDrop = function(aRow, aOrientation, ...aArgs) {
        var dropTargetFolder = gFolderTreeView._rowMap[aRow]._folder;
        if (dropTargetFolder &&
            DeleteOnlyEmptyFolder.isInTrash(dropTargetFolder) &&
            aOrientation === Ci.nsITreeView.DROP_ON) {
          let dt = this._currentTransfer;
          let types = dt.mozTypesAt(0);
          if (Array.indexOf(types, 'text/x-moz-folder') > -1) {
            for (let i = 0, maxi = dt.mozItemCount; i < maxi; i++) {
              let folder = dt.mozGetDataAt('text/x-moz-folder', i)
                             .QueryInterface(Ci.nsIMsgFolder);
              if (!DeleteOnlyEmptyFolder.isEmpty(folder)) {
                DeleteOnlyEmptyFolder.log('Dropped folder '+i+' is not empty..');
                return false;
              }
            }
          }
        }
        return gFolderTreeView.__delete_only_empty_folder__canDrop.apply(this, [aRow, aOrientation].concat(aArgs));
      };
    }
  };

  document.addEventListener('DOMContentLoaded', function onDOMContentLoaded(aEvent) {
    document.removeEventListener('DOMContentLoaded', onDOMContentLoaded);
    DeleteOnlyEmptyFolder.init();
  });

  aGlobal.DeleteOnlyEmptyFolder = DeleteOnlyEmptyFolder;
})(this);
<|endoftext|>


<commit_before>TestCase("HTMLElementsWillValidate", {

	"test willValidate should be false for hidden input": function() {
		/*:DOC field1 = <input type="hidden" /> */
		formerly.initElement(this.field1);

		assertFalse(this.field1.willValidate);
	},

	"test willValidate should be true for text input": function() {
		/*:DOC field1 = <input type="text" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for search input": function() {
		/*:DOC field1 = <input type="search" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for tel input": function() {
		/*:DOC field1 = <input type="tel" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for url input": function() {
		/*:DOC field1 = <input type="url" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for email input": function() {
		/*:DOC field1 = <input type="email" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for password input": function() {
		/*:DOC field1 = <input type="password" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for datetime input": function() {
		/*:DOC field1 = <input type="datetime" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for date input": function() {
		/*:DOC field1 = <input type="date" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for month input": function() {
		/*:DOC field1 = <input type="month" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for week input": function() {
		/*:DOC field1 = <input type="week" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for time input": function() {
		/*:DOC field1 = <input type="time" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for datetime local input": function() {
		/*:DOC field1 = <input type="datetime-local" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for number input": function() {
		/*:DOC field1 = <input type="number" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for range input": function() {
		/*:DOC field1 = <input type="range" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for color input": function() {
		/*:DOC field1 = <input type="color" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for checkbox input": function() {
		/*:DOC field1 = <input type="checkbox" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for radio input": function() {
		/*:DOC field1 = <input type="radio" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for file input": function() {
		/*:DOC field1 = <input type="file" /> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for submit input": function() {
		/*:DOC field1 = <input type="submit" /> */
		formerly.initElement(this.field1);

		//assertTrue(this.field1.willValidate);
		// False in Firefox 12.0 Mac OS
	},

	"test willValidate should be false for image input": function() {
		/*:DOC field1 = <input type="image" /> */
		formerly.initElement(this.field1);

		//assertFalse(this.field1.willValidate);
		// True in Opera 12.00 Mac OS
	},

	"test willValidate should be false for reset input": function() {
		/*:DOC field1 = <input type="reset" /> */
		formerly.initElement(this.field1);

		assertFalse(this.field1.willValidate);
	},

	"test willValidate should be false for button input": function() {
		/*:DOC field1 = <input type="button" /> */
		formerly.initElement(this.field1);

		assertFalse(this.field1.willValidate);
	},

	"test willValidate should be true for submit button": function() {
		/*:DOC field1 = <button type="submit" /> */
		formerly.initElement(this.field1);

		//assertTrue(this.field1.willValidate);
		// False in Firefox 12.0 Mac OS
	},

	"test willValidate should be false for reset button": function() {
		/*:DOC field1 = <button type="reset" /> */
		formerly.initElement(this.field1);

		assertFalse(this.field1.willValidate);
	},

	"test willValidate should be false for button button": function() {
		/*:DOC field1 = <button type="button" /> */
		formerly.initElement(this.field1);

		assertFalse(this.field1.willValidate);
	},

	"test willValidate should be false for fieldset": function() {
		/*:DOC field1 = <fieldset></fieldset> */
		formerly.initElement(this.field1);

		assertFalse(this.field1.willValidate);
	},

	"test willValidate should be false for keygen": function() {
		/*:DOC field1 = <keygen /> */
		formerly.initElement(this.field1);

		//assertFalse(this.field1.willValidate);
		// True in Firefox 12.0 Mac OS
	},

	"test willValidate should be false for object": function() {
		/*:DOC field1 = <object type="application/x-shockwave-flash" /> */
		formerly.initElement(this.field1);

		assertFalse(this.field1.willValidate);
	},

	"test willValidate should be false for output": function() {
		/*:DOC field1 = <output /> */
		formerly.initElement(this.field1);

		//assertFalse(this.field1.willValidate);
		// True in Firefox 12.0 Mac OS
	},

	"test willValidate should be true for select": function() {
		/*:DOC field1 = <select></select> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for select multiple": function() {
		/*:DOC field1 = <select multiple="multiple"></select> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be true for textarea": function() {
		/*:DOC field1 = <textarea></textarea> */
		formerly.initElement(this.field1);

		assertTrue(this.field1.willValidate);
	},

	"test willValidate should be false for disabled element": function() {
		/*:DOC field1 = <input type="text" disabled="disabled" /> */
		formerly.initElement(this.field1);

		assertFalse(this.field1.willValidate);
	},

	"test willValidate should be false for readonly element": function() {
		/*:DOC field1 = <input type="text" readonly="readonly" /> */
		formerly.initElement(this.field1);

		assertFalse(this.field1.willValidate);
	}
});

TestCase("HTMLElementsType", {

	"test type should be hidden for hidden input": function() {
		/*:DOC field1 = <input type="hidden" /> */
		formerly.initElement(this.field1);

		assertEquals("hidden", this.field1.getAttribute('type'));
		assertEquals("hidden", this.field1.type);
	},

	"test type should be text for text input": function() {
		/*:DOC field1 = <input type="text" /> */
		formerly.initElement(this.field1);

		assertEquals("text", this.field1.getAttribute('type'));
		assertEquals("text", this.field1.type);
	},

	"test type should be search for search input": function() {
		/*:DOC field1 = <input type="search" /> */
		formerly.initElement(this.field1);

		assertEquals("search", this.field1.getAttribute('type'));
		//assertEquals("search", this.field1.type);
		// 'text' in Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be tel for tel input": function() {
		/*:DOC field1 = <input type="tel" /> */
		formerly.initElement(this.field1);

		assertEquals("tel", this.field1.getAttribute('type'));
		//assertEquals("tel", this.field1.type);
		// 'text' in Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be url for url input": function() {
		/*:DOC field1 = <input type="url" /> */
		formerly.initElement(this.field1);

		assertEquals("url", this.field1.getAttribute('type'));
		//assertEquals("url", this.field1.type);
		// 'text' in Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be email for email input": function() {
		/*:DOC field1 = <input type="email" /> */
		formerly.initElement(this.field1);

		assertEquals("email", this.field1.getAttribute('type'));
		//assertEquals("email", this.field1.type);
		// 'text' in Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be password for password input": function() {
		/*:DOC field1 = <input type="password" /> */
		formerly.initElement(this.field1);

		assertEquals("password", this.field1.getAttribute('type'));
		assertEquals("password", this.field1.type);
	},

	"test type should be datetime for datetime input": function() {
		/*:DOC field1 = <input type="datetime" /> */
		formerly.initElement(this.field1);

		assertEquals("datetime", this.field1.getAttribute('type'));
		//assertEquals("datetime", this.field1.type);
		// 'text' in Firefox 12.0 Mac OS, Chrome 20.0.1132.57 Mac OS, and Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be date for date input": function() {
		/*:DOC field1 = <input type="date" /> */
		formerly.initElement(this.field1);

		assertEquals("date", this.field1.getAttribute('type'));
		//assertEquals("date", this.field1.type);
		// 'text' in Firefox 12.0 Mac OS and Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be month for month input": function() {
		/*:DOC field1 = <input type="month" /> */
		formerly.initElement(this.field1);

		assertEquals("month", this.field1.getAttribute('type'));
		//assertEquals("month", this.field1.type);
		// 'text' in Firefox 12.0 Mac OS, Chrome 20.0.1132.57 Mac OS, and Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be week for week input": function() {
		/*:DOC field1 = <input type="week" /> */
		formerly.initElement(this.field1);

		assertEquals("week", this.field1.getAttribute('type'));
		//assertEquals("week", this.field1.type);
		// 'text' in Firefox 12.0 Mac OS, Chrome 20.0.1132.57 Mac OS, and Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be time for time input": function() {
		/*:DOC field1 = <input type="time" /> */
		formerly.initElement(this.field1);

		assertEquals("time", this.field1.getAttribute('type'));
		//assertEquals("time", this.field1.type);
		// 'text' in Firefox 12.0 Mac OS, Chrome 20.0.1132.57 Mac OS, and Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be datetime-local for datetime local input": function() {
		/*:DOC field1 = <input type="datetime-local" /> */
		formerly.initElement(this.field1);

		assertEquals("datetime-local", this.field1.getAttribute('type'));
		//assertEquals("datetime-local", this.field1.type);
		// 'text' in Firefox 12.0 Mac OS, Chrome 20.0.1132.57 Mac OS, and Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be number for number input": function() {
		/*:DOC field1 = <input type="number" /> */
		formerly.initElement(this.field1);

		assertEquals("number", this.field1.getAttribute('type'));
		//assertEquals("number", this.field1.type);
		// 'text' in Firefox 12.0 Mac OS and Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be range for range input": function() {
		/*:DOC field1 = <input type="range" /> */
		formerly.initElement(this.field1);

		assertEquals("range", this.field1.getAttribute('type'));
		//assertEquals("range", this.field1.type);
		// 'text' in Firefox 12.0 Mac OS and Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be color for color input": function() {
		/*:DOC field1 = <input type="color" /> */
		formerly.initElement(this.field1);

		assertEquals("color", this.field1.getAttribute('type'));
		//assertEquals("color", this.field1.type);
		// 'text' in Firefox 12.0 Mac OS and Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be checkbox for checkbox input": function() {
		/*:DOC field1 = <input type="checkbox" /> */
		formerly.initElement(this.field1);

		assertEquals("checkbox", this.field1.getAttribute('type'));
		assertEquals("checkbox", this.field1.type);
	},

	"test type should be radio for radio input": function() {
		/*:DOC field1 = <input type="radio" /> */
		formerly.initElement(this.field1);

		assertEquals("radio", this.field1.getAttribute('type'));
		assertEquals("radio", this.field1.type);
	},

	"test type should be file for file input": function() {
		/*:DOC field1 = <input type="file" /> */
		formerly.initElement(this.field1);

		assertEquals("file", this.field1.getAttribute('type'));
		assertEquals("file", this.field1.type);
	},

	"test type should be submit for submit input": function() {
		/*:DOC field1 = <input type="submit" /> */
		formerly.initElement(this.field1);

		assertEquals("submit", this.field1.getAttribute('type'));
		assertEquals("submit", this.field1.type);
	},

	"test type should be image for image input": function() {
		/*:DOC field1 = <input type="image" /> */
		formerly.initElement(this.field1);

		assertEquals("image", this.field1.getAttribute('type'));
		assertEquals("image", this.field1.type);
	},

	"test type should be reset for reset input": function() {
		/*:DOC field1 = <input type="reset" /> */
		formerly.initElement(this.field1);

		assertEquals("reset", this.field1.getAttribute('type'));
		assertEquals("reset", this.field1.type);
	},

	"test type should be button for button input": function() {
		/*:DOC field1 = <input type="button" /> */
		formerly.initElement(this.field1);

		assertEquals("button", this.field1.getAttribute('type'));
		assertEquals("button", this.field1.type);
	},

	"test type should be submit for submit button": function() {
		/*:DOC field1 = <button type="submit" /> */
		formerly.initElement(this.field1);

		assertEquals("submit", this.field1.getAttribute('type'));
		assertEquals("submit", this.field1.type);
	},

	"test type should be reset for reset button": function() {
		/*:DOC field1 = <button type="reset" /> */
		formerly.initElement(this.field1);

		assertEquals("reset", this.field1.getAttribute('type'));
		assertEquals("reset", this.field1.type);
	},

	"test type should be button for button button": function() {
		/*:DOC field1 = <button type="button" /> */
		formerly.initElement(this.field1);

		assertEquals("button", this.field1.getAttribute('type'));
		assertEquals("button", this.field1.type);
	},

	"test type should be fieldset for fieldset": function() {
		/*:DOC field1 = <fieldset></fieldset> */
		formerly.initElement(this.field1);

		assertEquals("FIELDSET", this.field1.tagName);
		//assertEquals("fieldset", this.field1.type);
		// undefined in Safari 534.57.2 Mac OS, Opera 12.00 Mac OS, and Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be keygen for keygen": function() {
		/*:DOC field1 = <keygen /> */
		formerly.initElement(this.field1);

		//assertEquals("KEYGEN", this.field1.tagName);
		// 'SELECT' in Firefox 12.0 Mac OS
		//assertEquals("keygen", this.field1.type);
		// 'select-one' in Firefox 12.0 Mac OS
		// undefined in Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be a mime-type for object": function() {
		/*:DOC field1 = <object type="application/x-shockwave-flash" /> */
		formerly.initElement(this.field1);

		assertEquals("OBJECT", this.field1.tagName);
		assertEquals("application/x-shockwave-flash", this.field1.type);
	},

	"test type should be output for output": function() {
		/*:DOC field1 = <output /> */
		formerly.initElement(this.field1);

		assertEquals("OUTPUT", this.field1.tagName.toUpperCase());		// lowercase in IE8
		//assertEquals("output", this.field1.type);
		// undefined in Opera 12.00 Mac OS and Microsoft Internet Explorer 9.0 Windows
	},

	"test type should be select-one for select": function() {
		/*:DOC field1 = <select></select> */
		formerly.initElement(this.field1);

		assertEquals("SELECT", this.field1.tagName);
		assertEquals("select-one", this.field1.type);
	},

	"test type should be select-multiple for select multiple": function() {
		/*:DOC field1 = <select multiple="multiple"></select> */
		formerly.initElement(this.field1);

		assertEquals("SELECT", this.field1.tagName);
		assertEquals("select-multiple", this.field1.type);
	},

	"test type should be textarea for textarea": function() {
		/*:DOC field1 = <textarea></textarea> */
		formerly.initElement(this.field1);

		assertEquals("TEXTAREA", this.field1.tagName);
		assertEquals("textarea", this.field1.type);
	}

});

TestCase("HTMLElementsMaxLength", {
	"test should have maxLength 20": function () {
		/*:DOC field1 = <input type="text" maxlength="20" /> */
		assertEquals(20, this.field1.maxLength);
	},

	"test should have no maxLength": function () {
		/*:DOC field1 = <input type="text" /> */
		//assertEquals(524288, this.field1.maxLength);
		// -1 in Firefox 12.0 Mac OS and Opera 12.00 Mac OS
		// 2147483647 in Microsoft Internet Explorer 9.0 Windows
	},

	"test should have defaultValue": function () {
		/*:DOC field1 = <input type="text" value="A value" /> */
		assertEquals("A value", this.field1.defaultValue);
	}

});
<commit_msg>Moved HTML compatability tests out of formerly project<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/* jshint maxparams:5 */

var assert = require('assert');
var util = require('util');
var setTimeout = require('timers').setTimeout;

var Errors = require('../errors.js');
var TChannelJSON = require('../as/json');
var TChannelEndpointHandler = require('../endpoint-handler');

var MAX_RELAY_AD_ATTEMPTS = 2;
var RELAY_AD_RETRY_TIME = 1 * 1000;
var RELAY_AD_TIMEOUT = 50;

module.exports = HyperbahnHandler;

function HyperbahnHandler(options) {
    if (!(this instanceof HyperbahnHandler)) {
        return new HyperbahnHandler(options);
    }

    var self = this;
    TChannelEndpointHandler.call(self, 'hyperbahn');

    assert(options && options.channel, 'channel required');
    assert(options && options.egressNodes, 'egressNodes required');
    assert(options && options.callerName, 'callerName required');

    // TODO support blackList

    self.channel = options.channel;
    self.egressNodes = options.egressNodes;
    self.callerName = options.callerName;

    self.tchannelJSON = TChannelJSON({
        logger: self.channel.logger
    });

    // TODO replace JSON with real bufrw handlers for this
    self.tchannelJSON.register(self, 'ad', self,
        self.handleAdvertise);
    self.tchannelJSON.register(self, 'relay-ad', self,
        self.handleRelayAdvertise);

    self.relayAdTimeout = options.relayAdTimeout ||
        RELAY_AD_TIMEOUT;
    self.relayAdRetryTime = options.relayAdRetryTime ||
        RELAY_AD_RETRY_TIME;
    self.maxRelayAdAttempts = options.maxRelayAdAttempts ||
        MAX_RELAY_AD_ATTEMPTS;
}
util.inherits(HyperbahnHandler, TChannelEndpointHandler);

HyperbahnHandler.prototype.type = 'hyperbahn.advertisement-handler';

/*  req: {
        services: Array<{
            serviceName: String,
            cost: Number
        }>
    }

    res: {
        connectionCount: Number
    }
*/
HyperbahnHandler.prototype.handleAdvertise =
function handleAdvertise(self, req, arg2, arg3, cb) {
    /*eslint max-statements: [2, 25], max-params: [2, 5]*/
    var services = arg3.services;

    var servicesByExitNode = {};

    for (var i = 0; i < services.length; i++) {
        var service = services[i];
        service.hostPort = req.connection.remoteName;

        var serviceName = service.serviceName;
        if (serviceName === '') {
            continue;
        }

        var exitNodes = self.egressNodes.exitsFor(serviceName);
        var exitHosts = Object.keys(exitNodes);

        for (var j = 0; j < exitHosts.length; j++) {
            var exitNode = exitHosts[j];

            var relayReq = servicesByExitNode[exitNode];
            if (!relayReq) {
                relayReq = servicesByExitNode[exitNode] = [];
            }

            relayReq.push(service);
        }
    }

    var exitNodeKeys = Object.keys(servicesByExitNode);
    var counter = 1 + exitNodeKeys.length;
    for (var k = 0; k < exitNodeKeys.length; k++) {
        var hostPort = exitNodeKeys[k];
        var exitNodeServices = servicesByExitNode[hostPort];

        self.sendRelayAdvertise({
            hostPort: hostPort,
            services: exitNodeServices,
            inreq: req
        }, onFinish);
    }

    onFinish();

    // TODO remove blocking on fanout finish. Requires fixing
    // hyperbahn tests upstream
    function onFinish() {
        if (--counter === 0) {
            cb(null, {
                ok: true,
                head: null,
                body: {
                    connectionCount: exitNodeKeys.length
                }
            });
        }
    }
};

HyperbahnHandler.prototype.sendAdvertise =
function sendAdvertise(services, options, callback) {
    var self = this;

    if (typeof options === 'function') {
        callback = options;
        options = {};
    }

    options.serviceName = 'hyperbahn';
    options.trace = false;
    options.hasNoParent = true;
    options.headers = options.headers || {};
    options.headers.cn = self.callerName;

    var req = self.channel.request(options);
    self.tchannelJSON.send(req, 'ad', null, {
        services: services
    }, callback);
};

/*  req: {
        services: Array<{
            serviceName: String,
            hostPort: String,
            cost: Number
        }>
    }

    res: {}
*/
HyperbahnHandler.prototype.handleRelayAdvertise =
function handleRelayAdvertise(self, req, arg2, arg3, cb) {
    /*eslint max-params: [2, 5]*/
    var services = arg3.services;
    var logger = self.channel.logger;

    for (var i = 0; i < services.length; i++) {
        var service = services[i];

        var exitNodes = self.egressNodes
            .exitsFor(service.serviceName);
        var exitHosts = Object.keys(exitNodes);

        var myHost = self.channel.hostPort;
        if (exitHosts.indexOf(myHost) !== -1) {
            self.advertise(service);
        } else {
            logger.warn('Non-exit node got relay handle advertise', {
                myHost: myHost,
                exitHosts: exitHosts,
                service: service
            });
        }
    }

    cb(null, {
        ok: true,
        head: null,
        body: {}
    });
};

HyperbahnHandler.prototype.sendRelayAdvertise =
function sendRelayAdvertise(opts, callback) {
    var self = this;

    var attempts = 0;

    tryRequest();

    function tryRequest() {
        attempts++;

        self.channel.waitForIdentified({
            host: opts.hostPort
        }, onIdentified);

        function onIdentified(err) {
            if (err) {
                return onResponse(err);
            }

            self.tchannelJSON.send(self.channel.request({
                host: opts.hostPort,
                serviceName: 'hyperbahn',
                trace: false,
                timeout: self.relayAdTimeout,
                headers: {
                    cn: self.callerName
                },
                retryLimit: 1,
                parent: opts.inreq
            }), 'relay-ad', null, {
                services: opts.services
            }, onResponse);
        }

        function onResponse(err, response) {
            if (response && response.ok) {
                return callback(null, null);
            }

            var codeName = Errors.classify(err);

            if (attempts <= self.maxRelayAdAttempts && err &&
                (
                    codeName === 'NetworkError' ||
                    codeName === 'Timeout'
                )
            ) {
                setTimeout(tryRequest, self.relayAdRetryTime);
            } else {
                var logger = self.channel.logger;
                logger.error('Could not send relay advertise', {
                    exitNode: opts.hostPort,
                    services: opts.services,
                    error: err,
                    codeName: codeName,
                    responseBody: response && response.body
                });

                callback(null, null);
            }
        }
    }
};

HyperbahnHandler.prototype.advertise =
function advertise(service) {
    throw new Error('not implemented');
};
<commit_msg>hyperbahn: downgrade logging<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/* jshint maxparams:5 */

var assert = require('assert');
var util = require('util');
var setTimeout = require('timers').setTimeout;

var Errors = require('../errors.js');
var TChannelJSON = require('../as/json');
var TChannelEndpointHandler = require('../endpoint-handler');

var MAX_RELAY_AD_ATTEMPTS = 2;
var RELAY_AD_RETRY_TIME = 1 * 1000;
var RELAY_AD_TIMEOUT = 50;

module.exports = HyperbahnHandler;

function HyperbahnHandler(options) {
    if (!(this instanceof HyperbahnHandler)) {
        return new HyperbahnHandler(options);
    }

    var self = this;
    TChannelEndpointHandler.call(self, 'hyperbahn');

    assert(options && options.channel, 'channel required');
    assert(options && options.egressNodes, 'egressNodes required');
    assert(options && options.callerName, 'callerName required');

    // TODO support blackList

    self.channel = options.channel;
    self.egressNodes = options.egressNodes;
    self.callerName = options.callerName;

    self.tchannelJSON = TChannelJSON({
        logger: self.channel.logger
    });

    // TODO replace JSON with real bufrw handlers for this
    self.tchannelJSON.register(self, 'ad', self,
        self.handleAdvertise);
    self.tchannelJSON.register(self, 'relay-ad', self,
        self.handleRelayAdvertise);

    self.relayAdTimeout = options.relayAdTimeout ||
        RELAY_AD_TIMEOUT;
    self.relayAdRetryTime = options.relayAdRetryTime ||
        RELAY_AD_RETRY_TIME;
    self.maxRelayAdAttempts = options.maxRelayAdAttempts ||
        MAX_RELAY_AD_ATTEMPTS;
}
util.inherits(HyperbahnHandler, TChannelEndpointHandler);

HyperbahnHandler.prototype.type = 'hyperbahn.advertisement-handler';

/*  req: {
        services: Array<{
            serviceName: String,
            cost: Number
        }>
    }

    res: {
        connectionCount: Number
    }
*/
HyperbahnHandler.prototype.handleAdvertise =
function handleAdvertise(self, req, arg2, arg3, cb) {
    /*eslint max-statements: [2, 25], max-params: [2, 5]*/
    var services = arg3.services;

    var servicesByExitNode = {};

    for (var i = 0; i < services.length; i++) {
        var service = services[i];
        service.hostPort = req.connection.remoteName;

        var serviceName = service.serviceName;
        if (serviceName === '') {
            continue;
        }

        var exitNodes = self.egressNodes.exitsFor(serviceName);
        var exitHosts = Object.keys(exitNodes);

        for (var j = 0; j < exitHosts.length; j++) {
            var exitNode = exitHosts[j];

            var relayReq = servicesByExitNode[exitNode];
            if (!relayReq) {
                relayReq = servicesByExitNode[exitNode] = [];
            }

            relayReq.push(service);
        }
    }

    var exitNodeKeys = Object.keys(servicesByExitNode);
    var counter = 1 + exitNodeKeys.length;
    for (var k = 0; k < exitNodeKeys.length; k++) {
        var hostPort = exitNodeKeys[k];
        var exitNodeServices = servicesByExitNode[hostPort];

        self.sendRelayAdvertise({
            hostPort: hostPort,
            services: exitNodeServices,
            inreq: req
        }, onFinish);
    }

    onFinish();

    // TODO remove blocking on fanout finish. Requires fixing
    // hyperbahn tests upstream
    function onFinish() {
        if (--counter === 0) {
            cb(null, {
                ok: true,
                head: null,
                body: {
                    connectionCount: exitNodeKeys.length
                }
            });
        }
    }
};

HyperbahnHandler.prototype.sendAdvertise =
function sendAdvertise(services, options, callback) {
    var self = this;

    if (typeof options === 'function') {
        callback = options;
        options = {};
    }

    options.serviceName = 'hyperbahn';
    options.trace = false;
    options.hasNoParent = true;
    options.headers = options.headers || {};
    options.headers.cn = self.callerName;

    var req = self.channel.request(options);
    self.tchannelJSON.send(req, 'ad', null, {
        services: services
    }, callback);
};

/*  req: {
        services: Array<{
            serviceName: String,
            hostPort: String,
            cost: Number
        }>
    }

    res: {}
*/
HyperbahnHandler.prototype.handleRelayAdvertise =
function handleRelayAdvertise(self, req, arg2, arg3, cb) {
    /*eslint max-params: [2, 5]*/
    var services = arg3.services;
    var logger = self.channel.logger;

    for (var i = 0; i < services.length; i++) {
        var service = services[i];

        var exitNodes = self.egressNodes
            .exitsFor(service.serviceName);
        var exitHosts = Object.keys(exitNodes);

        var myHost = self.channel.hostPort;
        if (exitHosts.indexOf(myHost) !== -1) {
            self.advertise(service);
        } else {
            logger.warn('Non-exit node got relay handle advertise', {
                myHost: myHost,
                exitHosts: exitHosts,
                service: service
            });
        }
    }

    cb(null, {
        ok: true,
        head: null,
        body: {}
    });
};

HyperbahnHandler.prototype.sendRelayAdvertise =
function sendRelayAdvertise(opts, callback) {
    var self = this;

    var attempts = 0;

    tryRequest();

    function tryRequest() {
        attempts++;

        self.channel.waitForIdentified({
            host: opts.hostPort
        }, onIdentified);

        function onIdentified(err) {
            if (err) {
                return onResponse(err);
            }

            self.tchannelJSON.send(self.channel.request({
                host: opts.hostPort,
                serviceName: 'hyperbahn',
                trace: false,
                timeout: self.relayAdTimeout,
                headers: {
                    cn: self.callerName
                },
                retryLimit: 1,
                parent: opts.inreq
            }), 'relay-ad', null, {
                services: opts.services
            }, onResponse);
        }

        function onResponse(err, response) {
            if (response && response.ok) {
                return callback(null, null);
            }

            var codeName = Errors.classify(err);
            if (attempts <= self.maxRelayAdAttempts && err &&
                (
                    codeName === 'NetworkError' ||
                    codeName === 'Timeout'
                )
            ) {
                setTimeout(tryRequest, self.relayAdRetryTime);
            } else {
                self.logError(err, opts, response);

                callback(null, null);
            }
        }
    }
};

HyperbahnHandler.prototype.logError =
function logError(err, opts, response) {
    var self = this;

    var codeName = Errors.classify(err);
    var logger = self.channel.logger;

    var logOptions = {
        exitNode: opts.hostPort,
        services: opts.services,
        error: err,
        codeName: codeName,
        responseBody: response && response.body
    };

    if (codeName === 'NetworkError' ||
        codeName === 'Timeout'
    ) {
        logger.warn('Relay advertise failed with expected err', logOptions);
    } else {
        logger.error('Relay advertise failed with unexpected err', logOptions);
    }
};

HyperbahnHandler.prototype.advertise =
function advertise(service) {
    throw new Error('not implemented');
};
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

(function (aGlobal) {
  var Ci = Components.interfaces;
  var Cc = Components.classes;

  var tbBug766495 = {
    collectDraftFolders: function() {
      var accountManager = MailServices.accounts;
      var allServers = accountManager.allServers;
      for (var i = 0,  maxi = allServers.length; i < maxi; ++i) {
        let currentServer = allServers.queryElementAt(i, Ci.nsIMsgIncomingServer);
        if (currentServer.type == "none")
          continue;

        var folderURI = currentServer.rootFolder.server.serverURI + "/" + "Drafts";
      }
    }
  };

  document.addEventListener("DOMContentLoaded", function onDOMContentLoaded(aEvent) {
    document.removeEventListener("DOMContentLoaded", onDOMContentLoaded);
    tbBug766495.collectDraftFolders();
  });
  aGlobal.tbBug766495 = tbBug766495;
})(this);
<commit_msg>Create observer to create listener for imap folders<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

(function (aGlobal) {
  var Ci = Components.interfaces;
  var Cc = Components.classes;

  var tbBug766495 = {
    collectDraftFolders: function() {
      var accountManager = MailServices.accounts;
      var allServers = accountManager.allServers;
      for (var i = 0,  maxi = allServers.length; i < maxi; ++i) {
        let currentServer = allServers.queryElementAt(i, Ci.nsIMsgIncomingServer);
        if (currentServer.type == "none")
          continue;

        var folderURI = currentServer.rootFolder.server.serverURI + "/" + "Drafts";
      }
    },
    // nsIUrlListener
    createURLListenerForFolder: function createURLListenerForFolder() {
      return {
        OnStartRunningUrl: function OnStartRunningUrl(aURL) {
        },
        OnStopRunningUrl: function OnStopRunningUrl(aURL, aExitCode) {
          this.finished = true;
        },
        folder: aFolder,
        finished: false,
      };
    }
  };

  document.addEventListener("DOMContentLoaded", function onDOMContentLoaded(aEvent) {
    document.removeEventListener("DOMContentLoaded", onDOMContentLoaded);
    tbBug766495.collectDraftFolders();
  });
  aGlobal.tbBug766495 = tbBug766495;
})(this);
<|endoftext|>


<commit_before>/**
 * @fileOverview Borschik tech to freeze files in dir.
 */

process.env.BORSCHIK_FREEZABLE_EXTS = 'jpg jpeg gif ico png swf svg ttf eot otf woff css js swf';

var INHERIT = require('inherit');
var base = require('../tech');
var FS = require('../fs');
var PATH = require('path');
var FREEZE = require('borschik/lib/freeze');
var U = require('../util');

/**
 * Result JSON
 * @type {Object}
 */
var result = {};

exports.Tech = INHERIT(base.Tech, {

    process: function(path, out) {
        var basePath = PATH.dirname(path);
        var stat = FS.statSync(path);
        if (stat.isFile()) {
            processFile(path, process.cwd());

        } else if (stat.isDirectory()) {
            readDir(path, basePath);
        }

        return U.writeFile(out, this.opts.minimize? JSON.stringify(result) : JSON.stringify(result, null, 4));
    }
});

/**
 * Process file: freeze and write meta-data to result JSON
 * @param absPath
 * @param basePath
 */
function processFile(absPath, basePath) {
    var url = absPath;

    if (FREEZE.isFreezableUrl(url)) {
        url = FREEZE.processPath(url);
    }

    var relOriginalPath = PATH.relative(basePath, absPath);
    var resolved = FREEZE.resolveUrl2(url);
    url = (resolved == url ? PATH.relative(basePath, url) : resolved);

    result[relOriginalPath] = url;
}

/**
 * Read dir recursivly and process files
 * @param dir
 * @param basePath
 */
function readDir(dir, basePath) {
    FS.readdirSync(dir).forEach(function(file) {
        file = PATH.resolve(dir, file);
        var stat = FS.statSync(file);
        if (stat.isFile()) {
            processFile(file, basePath);

        } else if (stat.isDirectory()) {
            readDir(file, basePath);
        }
    });
}
<commit_msg>relative paths in require<commit_after>/**
 * @fileOverview Borschik tech to freeze files in dir.
 */

process.env.BORSCHIK_FREEZABLE_EXTS = 'jpg jpeg gif ico png swf svg ttf eot otf woff css js swf';

var INHERIT = require('inherit');
var base = require('../tech');
var FS = require('../fs');
var PATH = require('path');
var FREEZE = require('../freeze');
var U = require('../util');

/**
 * Result JSON
 * @type {Object}
 */
var result = {};

exports.Tech = INHERIT(base.Tech, {

    process: function(path, out) {
        var basePath = PATH.dirname(path);
        var stat = FS.statSync(path);
        if (stat.isFile()) {
            processFile(path, process.cwd());

        } else if (stat.isDirectory()) {
            readDir(path, basePath);
        }

        return U.writeFile(out, this.opts.minimize? JSON.stringify(result) : JSON.stringify(result, null, 4));
    }
});

/**
 * Process file: freeze and write meta-data to result JSON
 * @param absPath
 * @param basePath
 */
function processFile(absPath, basePath) {
    var url = absPath;

    if (FREEZE.isFreezableUrl(url)) {
        url = FREEZE.processPath(url);
    }

    var relOriginalPath = PATH.relative(basePath, absPath);
    var resolved = FREEZE.resolveUrl2(url);
    url = (resolved == url ? PATH.relative(basePath, url) : resolved);

    result[relOriginalPath] = url;
}

/**
 * Read dir recursivly and process files
 * @param dir
 * @param basePath
 */
function readDir(dir, basePath) {
    FS.readdirSync(dir).forEach(function(file) {
        file = PATH.resolve(dir, file);
        var stat = FS.statSync(file);
        if (stat.isFile()) {
            processFile(file, basePath);

        } else if (stat.isDirectory()) {
            readDir(file, basePath);
        }
    });
}
<|endoftext|>