<commit_before>window.onlad=gpf.loaded(function () {
    "uses strict";

    var
        Box = gpf.define("Box", {

            private: {

                "[_ui]": [gpf.$HtmlHandler()],
                _ui: null,

                _fileInput: null,

                "[_onBrowse]": [gpf.$HtmlEvent("click", "div.button.file")],
                _onBrowse: function(event) {
                    if (null === this._fileInput) {
                        // TODO find a better way to achieve this
                        var div = document.createElement("div");
                        div.innerHTML = "<input type=\"file\" id=\"sourceFile\" "
                            + "style=\"display: none;\">";

                        this._fileInput = this._ui.appendChild(div.firstChild);
                        // TODO see if it can be done automatically
                        gpf.html.handle(this);
                    }
                    this._fileInput.click();
                },

                "[_onBrowsed]": [gpf.$HtmlEvent("change", "input[type=file]")],
                _onBrowsed: function (event) {
                    var file = event.target.files[0];
                    alert(file.name);
                },

                "[_onDragOver]": [gpf.$HtmlEvent("dragover")],
                _onDragOver: function (event) {
                    // Check this is a file
                    event.stopPropagation();
                    event.preventDefault();
                    event.dataTransfer.dropEffect = 'copy';
                },

                "[_onDrop]": [gpf.$HtmlEvent("drop")],
                _onDrop: function (event) {
                    event.stopPropagation();
                    event.preventDefault();
                    var
                        files = event.dataTransfer.files,
                        len = files.length;
                    alert(event.dataTransfer.files[0].name);
                }

            }
        });

    var source = new Box();
    gpf.html.handle(source, "source");

});
<commit_msg>Selector fix<commit_after>window.onlad=gpf.loaded(function () {
    "uses strict";

    var
        Box = gpf.define("Box", {

            private: {

                "[_ui]": [gpf.$HtmlHandler()],
                _ui: null,

                _fileInput: null,

                "[_onBrowse]": [gpf.$HtmlEvent("click", "div.button.file")],
                _onBrowse: function(event) {
                    if (null === this._fileInput) {
                        // TODO find a better way to achieve this
                        var div = document.createElement("div");
                        div.innerHTML = "<input type=\"file\" id=\"sourceFile\" "
                            + "style=\"display: none;\">";

                        this._fileInput = this._ui.appendChild(div.firstChild);
                        // TODO see if it can be done automatically
                        gpf.html.handle(this);
                    }
                    this._fileInput.click();
                },

                "[_onBrowsed]": [gpf.$HtmlEvent("change", "input[type=file]")],
                _onBrowsed: function (event) {
                    var file = event.target.files[0];
                    alert(file.name);
                },

                "[_onDragOver]": [gpf.$HtmlEvent("dragover")],
                _onDragOver: function (event) {
                    // Check this is a file
                    event.stopPropagation();
                    event.preventDefault();
                    event.dataTransfer.dropEffect = 'copy';
                },

                "[_onDrop]": [gpf.$HtmlEvent("drop")],
                _onDrop: function (event) {
                    event.stopPropagation();
                    event.preventDefault();
                    var
                        files = event.dataTransfer.files,
                        len = files.length;
                    alert(event.dataTransfer.files[0].name);
                }

            }
        });

    var source = new Box();
    gpf.html.handle(source, "#source");

});
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.9.2
(function() {
  var CloudFormationTemplateContext, CoffeeScript, fs, path, vm,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    slice = [].slice;

  fs = require('fs');

  vm = require('vm');

  path = require('path');

  CoffeeScript = require('coffee-script');

  CloudFormationTemplateContext = (function() {
    function CloudFormationTemplateContext() {
      this.Description = bind(this.Description, this);
      this.Condition = bind(this.Condition, this);
      this.Output = bind(this.Output, this);
      this.Mapping = bind(this.Mapping, this);
      this._resourceByType = bind(this._resourceByType, this);
      this.DeclareResource = bind(this.DeclareResource, this);
      this._buildCall = bind(this._buildCall, this);
      this._paramByType = bind(this._paramByType, this);
      this._resources = {};
      this._parameters = {};
      this._mappings = null;
      this._outputs = {};
      this._description = null;
      this._conditions = null;
      this.Params = {};
      this.Resources = {};
      this.Mappings = {};
      this.Conditions = {};
      this.AWS = {
        AutoScaling: {
          AutoScalingGroup: null,
          LaunchConfiguration: null,
          ScalingPolicy: null,
          LifecycleHook: null,
          ScheduledAction: null,
          Trigger: null
        },
        CloudFormation: {
          Authentication: null,
          CustomResource: null,
          Stack: null,
          WaitCondition: null,
          WaitConditionHandle: null
        },
        CloudFront: {
          Distribution: null
        },
        CloudWatch: {
          Alarm: null
        },
        CodeDeploy: {
          Application: null,
          DeploymentConfig: null,
          DeploymentGroup: null
        },
        CloudTrail: {
          Trail: null
        },
        DataPipeline: {
          Pipeline: null
        },
        DynamoDB: {
          Table: null
        },
        EC2: {
          CustomerGateway: null,
          DHCPOptions: null,
          EIP: null,
          EIPAssociation: null,
          Instance: null,
          InternetGateway: null,
          NetworkAcl: null,
          NetworkAclEntry: null,
          NetworkInterface: null,
          Route: null,
          RouteTable: null,
          SecurityGroup: null,
          SecurityGroupIngress: null,
          SecurityGroupEgress: null,
          Subnet: null,
          SubnetNetworkAclAssociation: null,
          SubnetRouteTableAssociation: null,
          Volume: null,
          VolumeAttachment: null,
          VPC: null,
          VPCDHCPOptionsAssociation: null,
          VPCGatewayAttachment: null,
          VPNConnection: null,
          VPNGateway: null
        },
        ECS: {
          Cluser: null,
          Service: null,
          TaskDefinition: null
        },
        ElastiCache: {
          CacheCluster: null,
          ParameterGroup: null,
          SecurityGroup: null,
          SecurityGroupIngress: null
        },
        ElasticBeanstalk: {
          Application: null,
          Environment: null
        },
        ElasticLoadBalancing: {
          LoadBalancer: null
        },
        EFS: {
          FileSystem: null,
          MountTarget: null
        },
        IAM: {
          AccessKey: null,
          Group: null,
          InstanceProfile: null,
          Policy: null,
          Role: null,
          User: null,
          UserToGroupAddition: null
        },
        Kinesis: {
          Stream: null
        },
        Logs: {
          LogGroup: null,
          MetricFilter: null
        },
        Lambda: {
          Function: null,
          Permission: null,
          EventSourceMapping: null
        },
        OpsWorks: {
          App: null,
          Instance: null,
          Layer: null,
          Stack: null
        },
        Redshift: {
          Cluster: null,
          ClusterParameterGroup: null,
          ClusterSecurityGroup: null,
          ClusterSubnetGroup: null
        },
        RDS: {
          DBInstance: null,
          DBParameterGroup: null,
          DBSubnetGroup: null,
          DBSecurityGroup: null,
          DBSecurityGroupIngress: null
        },
        Route53: {
          RecordSet: null,
          RecordSetGroup: null,
          HostedZone: null,
          HealthCheck: null
        },
        SDB: {
          Domain: null
        },
        S3: {
          Bucket: null,
          BucketPolicy: null
        },
        SNS: {
          Topic: null,
          TopicPolicy: null
        },
        SQS: {
          Queue: null,
          QueuePolicy: null
        }
      };
      this.Param = {
        String: (function(_this) {
          return function(name, arg1, arg2) {
            return _this._paramByType('String', name, arg1, arg2);
          };
        })(this),
        Number: (function(_this) {
          return function(name, arg1, arg2) {
            return _this._paramByType('Number', name, arg1, arg2);
          };
        })(this),
        CommaDelimitedList: (function(_this) {
          return function(name, arg1, arg2) {
            return _this._paramByType('CommaDelimitedList', name, arg1, arg2);
          };
        })(this),
        AWS: (function(_this) {
          return function(type, name, arg1, arg2) {
            return _this._paramByType("AWS::" + type, name, arg1, arg2);
          };
        })(this),
        AWSList: (function(_this) {
          return function(type, name, arg1, arg2) {
            return _this._paramByType("List<" + type + ">", name, arg1, arg2);
          };
        })(this)
      };
      this._buildCall(null, null, 'AWS', this.AWS);
    }

    CloudFormationTemplateContext.prototype._paramByType = function(type, name, arg1, arg2) {
      var result;
      result = {};
      if (arg1 == null) {
        result[name] = {};
      } else if (arg2 == null) {
        result[name] = typeof arg1 === 'string' ? {
          Description: arg1
        } : arg1;
      } else {
        result[name] = arg2;
        result[name].Description = arg1;
      }
      result[name].Type = type;
      this._set(result, this._parameters);
      return this.Params[name] = {
        Ref: name
      };
    };

    CloudFormationTemplateContext.prototype._buildCall = function(parent, lastKey, awsType, leaf) {
      var key, val;
      if (leaf != null) {
        for (key in leaf) {
          val = leaf[key];
          this._buildCall(leaf, key, awsType + "::" + key, val);
        }
        return;
      }
      return parent[lastKey] = (function(_this) {
        return function(name, props) {
          return _this._resourceByType(awsType, name, props);
        };
      })(this);
    };

    CloudFormationTemplateContext.prototype.DeclareResource = function(name) {
      var base;
      return (base = this.Resources)[name] != null ? base[name] : base[name] = {
        Ref: name
      };
    };

    CloudFormationTemplateContext.prototype._resourceByType = function(type, name, props) {
      var result;
      result = {};
      if (((props != null ? props.Metadata : void 0) != null) || ((props != null ? props.Properties : void 0) != null) || ((props != null ? props.DependsOn : void 0) != null) || ((props != null ? props.UpdatePolicy : void 0) != null) || ((props != null ? props.CreationPolicy : void 0) != null) || ((props != null ? props.Condition : void 0) != null)) {
        result[name] = props;
        result[name].Type = type;
      } else {
        result[name] = {
          Type: type,
          Properties: props
        };
      }
      this._set(result, this._resources);
      return this.DeclareResource(name);
    };

    CloudFormationTemplateContext.prototype._set = function(source, target) {
      var key, results, val;
      results = [];
      for (key in source) {
        val = source[key];
        results.push(target[key] = val);
      }
      return results;
    };

    CloudFormationTemplateContext.prototype.Mapping = function(name, map) {
      var result;
      if (this._mappings == null) {
        this._mappings = {};
      }
      result = {};
      result[name] = map;
      return this._set(result, this._mappings);
    };

    CloudFormationTemplateContext.prototype.Output = function() {
      var args, name, result;
      name = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      result = {};
      if (args.length === 1) {
        result[name] = {
          Value: args[0]
        };
      }
      if (args.length === 2) {
        result[name] = {
          Description: args[0],
          Value: args[1]
        };
      }
      return this._set(result, this._outputs);
    };

    CloudFormationTemplateContext.prototype.Condition = function(name, intrinsicfn) {
      var result;
      if (this._conditions == null) {
        this._conditions = {};
      }
      result = {};
      result[name] = intrinsicfn;
      return this._set(result, this._conditions);
    };

    CloudFormationTemplateContext.prototype.Description = function(d) {
      return this._description = d;
    };

    CloudFormationTemplateContext.prototype.Tag = function(key, val) {
      return {
        Key: key,
        Value: val
      };
    };

    CloudFormationTemplateContext.prototype.Join = function() {
      var args, delimiter;
      delimiter = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      if (args.length === 1 && (args[0] instanceof Array)) {
        return {
          'Fn::Join': [delimiter, args[0]]
        };
      } else {
        return {
          'Fn::Join': [delimiter, args]
        };
      }
    };

    CloudFormationTemplateContext.prototype.FindInMap = function() {
      var args;
      args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
      return {
        'Fn::FindInMap': args
      };
    };

    CloudFormationTemplateContext.prototype.GetAtt = function() {
      var args;
      args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
      return {
        'Fn::GetAtt': args
      };
    };

    CloudFormationTemplateContext.prototype.Base64 = function(arg) {
      return {
        'Fn::Base64': arg
      };
    };

    CloudFormationTemplateContext.prototype.GetAZs = function(arg) {
      return {
        'Fn::GetAZs': arg
      };
    };

    CloudFormationTemplateContext.prototype.Select = function() {
      var args, index;
      index = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      if (args.length === 1 && (args[0] instanceof Array)) {
        return {
          'Fn::Select': [index, args[0]]
        };
      } else {
        return {
          'Fn::Select': [index, args]
        };
      }
    };

    CloudFormationTemplateContext.prototype.And = function() {
      var condition, conditions;
      condition = arguments[0], conditions = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      if (conditions.length === 1 && (conditions[0] instanceof Array)) {
        return {
          'Fn::And': [condition, conditions[0]]
        };
      } else {
        return {
          'Fn::And': [condition, conditions]
        };
      }
    };

    CloudFormationTemplateContext.prototype.Equals = function(value_1, value_2) {
      return {
        'Fn::Equals': [value_1, value_2]
      };
    };

    CloudFormationTemplateContext.prototype.If = function(condition, value_if_true, value_if_false) {
      return {
        'Fn::If': [condition, value_if_true, value_if_false]
      };
    };

    CloudFormationTemplateContext.prototype.Not = function(condition) {
      return {
        'Fn::Not': [condition]
      };
    };

    CloudFormationTemplateContext.prototype.Or = function() {
      var condition, conditions;
      condition = arguments[0], conditions = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      if (conditions.length === 1 && (conditions[0] instanceof Array)) {
        return {
          'Fn::Or': [condition, conditions[0]]
        };
      } else {
        return {
          'Fn::Or': [condition, conditions]
        };
      }
    };

    CloudFormationTemplateContext.prototype.AccountId = {
      Ref: 'AWS::AccountId'
    };

    CloudFormationTemplateContext.prototype.NotificationARNs = {
      Ref: 'AWS::NotificationARNs'
    };

    CloudFormationTemplateContext.prototype.NoValue = {
      Ref: 'AWS::NoValue'
    };

    CloudFormationTemplateContext.prototype.Region = {
      Ref: 'AWS::Region'
    };

    CloudFormationTemplateContext.prototype.StackId = {
      Ref: 'AWS::StackId'
    };

    CloudFormationTemplateContext.prototype.StackName = {
      Ref: 'AWS::StackName'
    };

    CloudFormationTemplateContext.prototype.InitScript = function(arg) {
      var chunks, compiled, existsSyncFunc, match, pattern, text;
      existsSyncFunc = fs.existsSync != null ? fs.existsSync : path.existsSync;
      if (!existsSyncFunc(arg)) {
        text = arg;
      } else {
        text = fs.readFileSync(arg).toString();
      }
      chunks = [];
      pattern = /((.|\n)*?)%{([^}?]+)}?((.|\n)*)/;
      match = text.match(pattern);
      while (match) {
        chunks.push(match[1]);
        compiled = CoffeeScript.compile(match[3], {
          bare: true
        });
        chunks.push(eval(compiled));
        text = match[4];
        match = text.match(pattern);
      }
      if (text && text.length > 0) {
        chunks.push(text);
      }
      return this.Base64(this.Join('', chunks));
    };

    return CloudFormationTemplateContext;

  })();

  module.exports.CloudFormationTemplateContext = CloudFormationTemplateContext;

  module.exports = function(func) {
    var context, template;
    context = new CloudFormationTemplateContext;
    func.apply(context, [context]);
    template = {
      AWSTemplateFormatVersion: '2010-09-09'
    };
    if (context._description != null) {
      template.Description = context._description;
    }
    template.Parameters = context._parameters;
    if (context._mappings != null) {
      template.Mappings = context._mappings;
    }
    template.Resources = context._resources;
    template.Outputs = context._outputs;
    if (context._conditions != null) {
      template.Conditions = context._conditions;
    }
    return template;
  };

  require('pkginfo')(module, 'version');

}).call(this);
<commit_msg>update lib<commit_after>// Generated by CoffeeScript 1.9.2
(function() {
  var CloudFormationTemplateContext, CoffeeScript, fs, path, vm,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    slice = [].slice;

  fs = require('fs');

  vm = require('vm');

  path = require('path');

  CoffeeScript = require('coffee-script');

  CloudFormationTemplateContext = (function() {
    function CloudFormationTemplateContext() {
      this.Description = bind(this.Description, this);
      this.Condition = bind(this.Condition, this);
      this.Output = bind(this.Output, this);
      this.Mapping = bind(this.Mapping, this);
      this._resourceByType = bind(this._resourceByType, this);
      this.DeclareResource = bind(this.DeclareResource, this);
      this._buildCall = bind(this._buildCall, this);
      this._paramByType = bind(this._paramByType, this);
      this._resources = {};
      this._parameters = {};
      this._mappings = null;
      this._outputs = {};
      this._description = null;
      this._conditions = null;
      this.Params = {};
      this.Resources = {};
      this.Mappings = {};
      this.Conditions = {};
      this.AWS = {
        AutoScaling: {
          AutoScalingGroup: null,
          LaunchConfiguration: null,
          ScalingPolicy: null,
          LifecycleHook: null,
          ScheduledAction: null,
          Trigger: null
        },
        CloudFormation: {
          Authentication: null,
          CustomResource: null,
          Stack: null,
          WaitCondition: null,
          WaitConditionHandle: null
        },
        CloudFront: {
          Distribution: null
        },
        CloudWatch: {
          Alarm: null
        },
        CodeDeploy: {
          Application: null,
          DeploymentConfig: null,
          DeploymentGroup: null
        },
        CloudTrail: {
          Trail: null
        },
        DataPipeline: {
          Pipeline: null
        },
        DynamoDB: {
          Table: null
        },
        EC2: {
          CustomerGateway: null,
          DHCPOptions: null,
          EIP: null,
          EIPAssociation: null,
          Instance: null,
          InternetGateway: null,
          NetworkAcl: null,
          NetworkAclEntry: null,
          NetworkInterface: null,
          Route: null,
          RouteTable: null,
          SecurityGroup: null,
          SecurityGroupIngress: null,
          SecurityGroupEgress: null,
          Subnet: null,
          SubnetNetworkAclAssociation: null,
          SubnetRouteTableAssociation: null,
          Volume: null,
          VolumeAttachment: null,
          VPC: null,
          VPCDHCPOptionsAssociation: null,
          VPCGatewayAttachment: null,
          VPNConnection: null,
          VPNGateway: null
        },
        ECS: {
          Cluser: null,
          Service: null,
          TaskDefinition: null
        },
        ElastiCache: {
          CacheCluster: null,
          ParameterGroup: null,
          SecurityGroup: null,
          SecurityGroupIngress: null
        },
        ElasticBeanstalk: {
          Application: null,
          ApplicationVersion: null,
          Environment: null,
          ConfigurationTemplate: null
        },
        ElasticLoadBalancing: {
          LoadBalancer: null
        },
        EFS: {
          FileSystem: null,
          MountTarget: null
        },
        IAM: {
          AccessKey: null,
          Group: null,
          InstanceProfile: null,
          Policy: null,
          Role: null,
          User: null,
          UserToGroupAddition: null
        },
        Kinesis: {
          Stream: null
        },
        Logs: {
          LogGroup: null,
          MetricFilter: null
        },
        Lambda: {
          Function: null,
          Permission: null,
          EventSourceMapping: null
        },
        OpsWorks: {
          App: null,
          Instance: null,
          Layer: null,
          Stack: null
        },
        Redshift: {
          Cluster: null,
          ClusterParameterGroup: null,
          ClusterSecurityGroup: null,
          ClusterSubnetGroup: null
        },
        RDS: {
          DBInstance: null,
          DBParameterGroup: null,
          DBSubnetGroup: null,
          DBSecurityGroup: null,
          DBSecurityGroupIngress: null
        },
        Route53: {
          RecordSet: null,
          RecordSetGroup: null,
          HostedZone: null,
          HealthCheck: null
        },
        SDB: {
          Domain: null
        },
        S3: {
          Bucket: null,
          BucketPolicy: null
        },
        SNS: {
          Topic: null,
          TopicPolicy: null
        },
        SQS: {
          Queue: null,
          QueuePolicy: null
        }
      };
      this.Param = {
        String: (function(_this) {
          return function(name, arg1, arg2) {
            return _this._paramByType('String', name, arg1, arg2);
          };
        })(this),
        Number: (function(_this) {
          return function(name, arg1, arg2) {
            return _this._paramByType('Number', name, arg1, arg2);
          };
        })(this),
        CommaDelimitedList: (function(_this) {
          return function(name, arg1, arg2) {
            return _this._paramByType('CommaDelimitedList', name, arg1, arg2);
          };
        })(this),
        AWS: (function(_this) {
          return function(type, name, arg1, arg2) {
            return _this._paramByType("AWS::" + type, name, arg1, arg2);
          };
        })(this),
        AWSList: (function(_this) {
          return function(type, name, arg1, arg2) {
            return _this._paramByType("List<" + type + ">", name, arg1, arg2);
          };
        })(this)
      };
      this._buildCall(null, null, 'AWS', this.AWS);
    }

    CloudFormationTemplateContext.prototype._paramByType = function(type, name, arg1, arg2) {
      var result;
      result = {};
      if (arg1 == null) {
        result[name] = {};
      } else if (arg2 == null) {
        result[name] = typeof arg1 === 'string' ? {
          Description: arg1
        } : arg1;
      } else {
        result[name] = arg2;
        result[name].Description = arg1;
      }
      result[name].Type = type;
      this._set(result, this._parameters);
      return this.Params[name] = {
        Ref: name
      };
    };

    CloudFormationTemplateContext.prototype._buildCall = function(parent, lastKey, awsType, leaf) {
      var key, val;
      if (leaf != null) {
        for (key in leaf) {
          val = leaf[key];
          this._buildCall(leaf, key, awsType + "::" + key, val);
        }
        return;
      }
      return parent[lastKey] = (function(_this) {
        return function(name, props) {
          return _this._resourceByType(awsType, name, props);
        };
      })(this);
    };

    CloudFormationTemplateContext.prototype.DeclareResource = function(name) {
      var base;
      return (base = this.Resources)[name] != null ? base[name] : base[name] = {
        Ref: name
      };
    };

    CloudFormationTemplateContext.prototype._resourceByType = function(type, name, props) {
      var result;
      result = {};
      if (((props != null ? props.Metadata : void 0) != null) || ((props != null ? props.Properties : void 0) != null) || ((props != null ? props.DependsOn : void 0) != null) || ((props != null ? props.UpdatePolicy : void 0) != null) || ((props != null ? props.CreationPolicy : void 0) != null) || ((props != null ? props.Condition : void 0) != null)) {
        result[name] = props;
        result[name].Type = type;
      } else {
        result[name] = {
          Type: type,
          Properties: props
        };
      }
      this._set(result, this._resources);
      return this.DeclareResource(name);
    };

    CloudFormationTemplateContext.prototype._set = function(source, target) {
      var key, results, val;
      results = [];
      for (key in source) {
        val = source[key];
        results.push(target[key] = val);
      }
      return results;
    };

    CloudFormationTemplateContext.prototype.Mapping = function(name, map) {
      var result;
      if (this._mappings == null) {
        this._mappings = {};
      }
      result = {};
      result[name] = map;
      return this._set(result, this._mappings);
    };

    CloudFormationTemplateContext.prototype.Output = function() {
      var args, name, result;
      name = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      result = {};
      if (args.length === 1) {
        result[name] = {
          Value: args[0]
        };
      }
      if (args.length === 2) {
        result[name] = {
          Description: args[0],
          Value: args[1]
        };
      }
      return this._set(result, this._outputs);
    };

    CloudFormationTemplateContext.prototype.Condition = function(name, intrinsicfn) {
      var result;
      if (this._conditions == null) {
        this._conditions = {};
      }
      result = {};
      result[name] = intrinsicfn;
      return this._set(result, this._conditions);
    };

    CloudFormationTemplateContext.prototype.Description = function(d) {
      return this._description = d;
    };

    CloudFormationTemplateContext.prototype.Tag = function(key, val) {
      return {
        Key: key,
        Value: val
      };
    };

    CloudFormationTemplateContext.prototype.Join = function() {
      var args, delimiter;
      delimiter = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      if (args.length === 1 && (args[0] instanceof Array)) {
        return {
          'Fn::Join': [delimiter, args[0]]
        };
      } else {
        return {
          'Fn::Join': [delimiter, args]
        };
      }
    };

    CloudFormationTemplateContext.prototype.FindInMap = function() {
      var args;
      args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
      return {
        'Fn::FindInMap': args
      };
    };

    CloudFormationTemplateContext.prototype.GetAtt = function() {
      var args;
      args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
      return {
        'Fn::GetAtt': args
      };
    };

    CloudFormationTemplateContext.prototype.Base64 = function(arg) {
      return {
        'Fn::Base64': arg
      };
    };

    CloudFormationTemplateContext.prototype.GetAZs = function(arg) {
      return {
        'Fn::GetAZs': arg
      };
    };

    CloudFormationTemplateContext.prototype.Select = function() {
      var args, index;
      index = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      if (args.length === 1 && (args[0] instanceof Array)) {
        return {
          'Fn::Select': [index, args[0]]
        };
      } else {
        return {
          'Fn::Select': [index, args]
        };
      }
    };

    CloudFormationTemplateContext.prototype.And = function() {
      var condition, conditions;
      condition = arguments[0], conditions = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      if (conditions.length === 1 && (conditions[0] instanceof Array)) {
        return {
          'Fn::And': [condition, conditions[0]]
        };
      } else {
        return {
          'Fn::And': [condition, conditions]
        };
      }
    };

    CloudFormationTemplateContext.prototype.Equals = function(value_1, value_2) {
      return {
        'Fn::Equals': [value_1, value_2]
      };
    };

    CloudFormationTemplateContext.prototype.If = function(condition, value_if_true, value_if_false) {
      return {
        'Fn::If': [condition, value_if_true, value_if_false]
      };
    };

    CloudFormationTemplateContext.prototype.Not = function(condition) {
      return {
        'Fn::Not': [condition]
      };
    };

    CloudFormationTemplateContext.prototype.Or = function() {
      var condition, conditions;
      condition = arguments[0], conditions = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      if (conditions.length === 1 && (conditions[0] instanceof Array)) {
        return {
          'Fn::Or': [condition, conditions[0]]
        };
      } else {
        return {
          'Fn::Or': [condition, conditions]
        };
      }
    };

    CloudFormationTemplateContext.prototype.AccountId = {
      Ref: 'AWS::AccountId'
    };

    CloudFormationTemplateContext.prototype.NotificationARNs = {
      Ref: 'AWS::NotificationARNs'
    };

    CloudFormationTemplateContext.prototype.NoValue = {
      Ref: 'AWS::NoValue'
    };

    CloudFormationTemplateContext.prototype.Region = {
      Ref: 'AWS::Region'
    };

    CloudFormationTemplateContext.prototype.StackId = {
      Ref: 'AWS::StackId'
    };

    CloudFormationTemplateContext.prototype.StackName = {
      Ref: 'AWS::StackName'
    };

    CloudFormationTemplateContext.prototype.InitScript = function(arg) {
      var chunks, compiled, existsSyncFunc, match, pattern, text;
      existsSyncFunc = fs.existsSync != null ? fs.existsSync : path.existsSync;
      if (!existsSyncFunc(arg)) {
        text = arg;
      } else {
        text = fs.readFileSync(arg).toString();
      }
      chunks = [];
      pattern = /((.|\n)*?)%{([^}?]+)}?((.|\n)*)/;
      match = text.match(pattern);
      while (match) {
        chunks.push(match[1]);
        compiled = CoffeeScript.compile(match[3], {
          bare: true
        });
        chunks.push(eval(compiled));
        text = match[4];
        match = text.match(pattern);
      }
      if (text && text.length > 0) {
        chunks.push(text);
      }
      return this.Base64(this.Join('', chunks));
    };

    return CloudFormationTemplateContext;

  })();

  module.exports.CloudFormationTemplateContext = CloudFormationTemplateContext;

  module.exports = function(func) {
    var context, template;
    context = new CloudFormationTemplateContext;
    func.apply(context, [context]);
    template = {
      AWSTemplateFormatVersion: '2010-09-09'
    };
    if (context._description != null) {
      template.Description = context._description;
    }
    template.Parameters = context._parameters;
    if (context._mappings != null) {
      template.Mappings = context._mappings;
    }
    template.Resources = context._resources;
    template.Outputs = context._outputs;
    if (context._conditions != null) {
      template.Conditions = context._conditions;
    }
    return template;
  };

  require('pkginfo')(module, 'version');

}).call(this);
<|endoftext|>


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

const {gen: tcg} = require('testcheck');

const {invalidString} = require('./conform');
const {explainData} = require('./explainData');
const {gen} = require('./gen');
const {checkCount} = require('./util/helper');
const isValid = require('./isValid');

const describe = require('./util/describe');

function collOf(predicate, options = {}) {
    const {kind = () => true, distinct = false, into} = options;
    const uniq = value => !distinct || isUnique(value);

    return {
        conform: value => {
            const result = kind(value) && uniq(value) && checkCount(value, options)
                  && _.every(value, v => isValid(predicate, v));
            return result ? transform(value, into) : invalidString;
        },
        unform: _.identity,
        gen: () => tcg.null.then(() => {
            const count = options.count || 10;
            return tcg.array(gen(predicate), {size: count});
        }),
        describe: () => [collOf.name, ...describe([predicate]), ...describe(_.flatten(_.toPairs(options)))],
        explain: function*(values, {via}) {
            yield* explainCount(values, options, via);
            yield* explainInvalid(values, predicate, via);
        }
    };
}

function* explainCount(values, {count, minCount, maxCount} = {}, via) {
    if (count) {
        const f = new Function('', `return values => values.length === ${count}`)();
        if (!f(values)) {
            yield {
                path: [],
                pred: `${f}`,
                val: values,
                via,
                'in': []
            };
        }
    }
}

function* explainInvalid([v, ...rest], predicate, via, index = 0) {
    if (v) {
        if (!isValid(predicate, v)) {
            yield explainData(predicate, v, {via, _in: [index]}).problems[0];
        }
        yield* explainInvalid(rest, predicate, via, ++index);
    }
}

function isUnique(value) {
    return _.uniq(value).length === value.length;
}

function transform(value, into) {
    if (_.isSet(into)) {
        return new Set(value);
    } else if (_.isArray(into)) {
        return [...value];
    }
    return value;
}

module.exports = collOf;
<commit_msg>Improve mutation test<commit_after>const _ = require('lodash');

const {gen: tcg} = require('testcheck');

const {invalidString} = require('./conform');
const {explainData} = require('./explainData');
const {gen} = require('./gen');
const {checkCount} = require('./util/helper');
const isValid = require('./isValid');

const describe = require('./util/describe');

function collOf(predicate, options = {}) {
    const {kind = () => true, distinct = false, into} = options;
    const uniq = value => !distinct || isUnique(value);

    return {
        conform: value => {
            const result = kind(value) && uniq(value) && checkCount(value, options)
                  && _.every(value, v => isValid(predicate, v));
            return result ? transform(value, into) : invalidString;
        },
        unform: _.identity,
        gen: () => tcg.null.then(() => tcg.array(gen(predicate), {size: options.count})),
        describe: () => [collOf.name, ...describe([predicate]), ...describe(_.flatten(_.toPairs(options)))],
        explain: function*(values, {via}) {
            yield* explainCount(values, options, via);
            yield* explainInvalid(values, predicate, via);
        }
    };
}

function* explainCount(values, {count, minCount, maxCount} = {}, via) {
    if (count) {
        const f = new Function('', `return values => values.length === ${count}`)();
        if (!f(values)) {
            yield {
                path: [],
                pred: `${f}`,
                val: values,
                via,
                'in': []
            };
        }
    }
}

function* explainInvalid([v, ...rest], predicate, via, index = 0) {
    if (v) {
        if (!isValid(predicate, v)) {
            yield explainData(predicate, v, {via, _in: [index]}).problems[0];
        }
        yield* explainInvalid(rest, predicate, via, ++index);
    }
}

function isUnique(value) {
    return _.uniq(value).length === value.length;
}

function transform(value, into) {
    if (_.isSet(into)) {
        return new Set(value);
    } else if (_.isArray(into)) {
        return [...value];
    }
    return value;
}

module.exports = collOf;
<|endoftext|>


<commit_before>var map = require('map-stream');
var gutil = require('gulp-util');
var exec = require('child_process').exec;
var escape = require('any-shell-escape');

module.exports = function (message, opt) {
  if(!opt) opt = {};
  if(!message) throw new Error('gulp-git: Commit message is required git.commit("commit message")');
  if(!opt.args) opt.args = '';

  function commit(file, cb) {
    var cmd = 'git commit -m "' + message + '" ' + escape([file.path]) + ' ' + opt.args;
    exec(cmd, {cwd: file.cwd}, function(err, stdout, stderr){
      if(err) gutil.log(err);
      gutil.log(stdout, stderr);
      cb(null, file);
    });
  }

  // Return a stream
  return map(commit);
};<commit_msg>through obj<commit_after>var through = require('through2');
var gutil = require('gulp-util');
var exec = require('child_process').exec;
var escape = require('any-shell-escape');

module.exports = function (message, opt) {
  if(!opt) opt = {};
  if(!message) throw new Error('gulp-git: Commit message is required git.commit("commit message")');
  if(!opt.args) opt.args = ' ';

  var files = [];
  var cwd = '';

  var stream = through.obj(function(file, enc, cb){
    this.push(file);
    files.push(file.path);
    cwd = file.cwd;
    cb();
  }).on('data', function(){

  }).on('end', function(){
    var cmd = 'git commit -m "' + message + '" ' + escape(files) + ' ' + opt.args;
      exec(cmd, {cwd: cwd}, function(err, stdout, stderr){
        if(err) gutil.log(err);
        gutil.log(stdout, stderr);
    });
  });

  return stream;
};<|endoftext|>


<commit_before>'use strict';

const OFF = 'off';
const ERROR = 'error';
const WARN = 'warn';

const COMPLEXITY_MAX = 5;
const TABWIDTH = 2;
const NESTED_CALLBACK_MAX = 4;
const ARGUMENTS_MAX = 4;

module.exports = {
  extends: 'eslint:recommended',
  env: {
    node: true,
  },
  globals: {
    require: false,
    module: false,
  },
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'script',
    arrowFunctions: true,
    binaryLiterals: true,
    blockBindings: true,
    classes: false,
    defaultParams: true,
    destructuring: true,
    forOf: true,
    generators: false,
    modules: false,
    objectLiteralComputedProperties: true,
    objectLiteralDuplicateProperties: true,
    objectLiteralShorthandMethods: true,
    objectLiteralShorthandProperties: true,
    octalLiterals: false,
    regexUFlag: true,
    regexYFlag: true,
    restParams: true,
    spread: true,
    superInFunctions: true,
    templateStrings: true,
    unicodeCodePointEscapes: true,
  },
  rules: {
    'accessor-pairs': [ERROR, { getWithoutSet: false, setWithoutGet: true }],
    'array-bracket-newline': OFF,
    'array-bracket-spacing': [ERROR, 'never'],
    'array-callback-return': ERROR,
    'array-element-newline': OFF,
    'arrow-body-style': [ERROR, 'as-needed'],
    'arrow-parens': [ERROR, 'as-needed'],
    'arrow-spacing': ERROR,
    'block-spacing': [ERROR, 'always'],
    'brace-style': OFF,
    'callback-return': [ERROR, ['callback', 'cb', 'next', 'done']],
    camelcase: OFF,
    'capitalized-comments': OFF,
    'class-methods-use-this': ERROR,
    'comma-dangle': [ERROR, 'always-multiline'],
    'comma-spacing': [ERROR, { before: false, after: true }],
    'comma-style': [ERROR, 'last'],
    complexity: [WARN, COMPLEXITY_MAX],
    'computed-property-spacing': [ERROR, 'never'],
    'consistent-return': ERROR,
    'consistent-this': [ERROR, '_this'],
    'constructor-super': ERROR,
    curly: ERROR,
    'default-case': ERROR,
    'dot-location': [ERROR, 'property'],
    'dot-notation': ERROR,
    'eol-last': ERROR,
    eqeqeq: [ERROR, 'smart'],
    'for-direction': ERROR,
    'func-call-spacing': [ERROR, 'never'],
    'func-names': WARN,
    'func-name-matching': OFF,
    'func-style': [ERROR, 'declaration', { allowArrowFunctions: true }],
    'function-paren-newline': OFF,
    'getter-return': ERROR,
    'global-require': ERROR,
    'guard-for-in': ERROR,
    'handle-callback-err': ERROR,
    'id-blacklist': OFF,
    'id-length': OFF,
    'id-match': OFF,
    indent: OFF,
    'init-declarations': OFF,
    'jsx-quotes': OFF,
    'key-spacing': [ERROR, { beforeColon: false, afterColon: true }],
    'lines-between-class-members': OFF,
    'line-comment-position': OFF,
    'linebreak-style': [ERROR, 'unix'],
    'lines-around-comment': OFF,
    'lines-around-directive': OFF,
    'max-len': [
      WARN,
      100,
      TABWIDTH,
      {
        ignoreComments: true,
        ignorePattern: '^\\s*import\\s.+\\sfrom\\s.+;$',
      },
    ],
    'max-classes-per-file': OFF,
    'max-lines': [WARN, { max: 1000 }],
    'max-lines-per-function': OFF,
    'max-nested-callbacks': [ERROR, NESTED_CALLBACK_MAX],
    'max-params': [ERROR, ARGUMENTS_MAX],
    'max-statements-per-line': [WARN, { max: 2 }],
    'multiline-comment-style': OFF,
    'multiline-ternary': OFF,
    'new-cap': [ERROR, { newIsCap: true, capIsNew: true }],
    'new-parens': ERROR,
    'newline-after-var': WARN,
    'newline-before-return': OFF,
    'newline-per-chained-call': OFF,
    'no-alert': ERROR,
    'no-array-constructor': ERROR,
    'no-await-in-loop': OFF,
    'no-buffer-constructor': ERROR,
    'no-caller': ERROR,
    'no-case-declarations': ERROR,
    'no-catch-shadow': ERROR,
    'no-class-assign': ERROR,
    'no-compare-neg-zero': ERROR,
    'no-confusing-arrow': OFF,
    'no-cond-assign': ERROR,
    'no-console': ERROR,
    'no-const-assign': ERROR,
    'no-constant-condition': ERROR,
    'no-continue': OFF,
    'no-control-regex': ERROR,
    'no-debugger': ERROR,
    'no-delete-var': ERROR,
    'no-div-regex': ERROR,
    'no-dupe-args': ERROR,
    'no-dupe-class-members': OFF,
    'no-dupe-keys': ERROR,
    'no-duplicate-case': ERROR,
    'no-duplicate-imports': ERROR,
    'no-else-return': ERROR,
    'no-empty': ERROR,
    'no-empty-character-class': ERROR,
    'no-empty-pattern': ERROR,
    'no-global-assign': ERROR,
    'no-labels': ERROR,
    'no-eq-null': ERROR,
    'no-eval': ERROR,
    'no-ex-assign': ERROR,
    'no-extend-native': ERROR,
    'no-extra-bind': ERROR,
    'no-extra-boolean-cast': ERROR,
    'no-extra-label': OFF,
    'no-extra-parens': OFF,
    'no-extra-semi': ERROR,
    'no-fallthrough': ERROR,
    'no-floating-decimal': ERROR,
    'no-func-assign': ERROR,
    'no-implicit-coercion': OFF,
    'no-implicit-globals': OFF,
    'no-implied-eval': ERROR,
    'no-inline-comments': OFF,
    'no-inner-declarations': ERROR,
    'no-invalid-regexp': ERROR,
    'no-invalid-this': WARN,
    'no-irregular-whitespace': ERROR,
    'no-iterator': ERROR,
    'no-label-var': ERROR,
    'no-lone-blocks': ERROR,
    'no-lonely-if': ERROR,
    'no-loop-func': ERROR,
    'no-magic-numbers': [
      ERROR,
      {
        ignoreArrayIndexes: true,
        ignore: [
          -1,
          0,
          1,
          100,
          101,
          102,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          210,
          226,
          300,
          301,
          302,
          303,
          304,
          305,
          306,
          307,
          308,
          310,
          400,
          401,
          402,
          403,
          404,
          405,
          406,
          407,
          408,
          409,
          410,
          411,
          412,
          413,
          414,
          415,
          416,
          417,
          418,
          421,
          422,
          423,
          424,
          425,
          426,
          427,
          428,
          429,
          431,
          449,
          450,
          451,
          456,
          499,
          500,
          501,
          502,
          503,
          504,
          505,
          506,
          507,
          508,
          509,
          510,
          511,
          520,
        ],
      },
    ],
    'no-mixed-operators': OFF,
    'no-mixed-requires': OFF,
    'no-mixed-spaces-and-tabs': ERROR,
    'no-multi-spaces': ERROR,
    'no-multi-str': ERROR,
    'no-multiple-empty-lines': [ERROR, { max: 2 }],
    'no-native-reassign': ERROR,
    'no-negated-condition': OFF,
    'no-negated-in-lhs': ERROR,
    'no-nested-ternary': OFF,
    'no-new': WARN,
    'no-new-func': ERROR,
    'no-new-object': ERROR,
    'no-new-require': ERROR,
    'no-new-symbol': ERROR,
    'no-obj-calls': ERROR,
    'no-octal': ERROR,
    'no-octal-escape': ERROR,
    'no-param-reassign': OFF,
    'no-path-concat': ERROR,
    'no-process-env': OFF,
    'no-process-exit': OFF,
    'no-proto': ERROR,
    'no-prototype-builtins': WARN,
    'no-redeclare': ERROR,
    'no-regex-spaces': ERROR,
    'no-reserved-keys': OFF,
    'no-restricted-globals': OFF,
    'no-restricted-imports': OFF,
    'no-restricted-modules': OFF,
    'no-restricted-syntax': OFF,
    'no-restricted-properties': [
      ERROR,
      {
        object: 'describe',
        property: 'only',
        message: 'Using describe.only is not allowed',
      },
      {
        object: 'it',
        property: 'only',
        message: 'Using it.only is not allowed',
      },
    ],
    'no-return-assign': ERROR,
    'no-return-await': ERROR,
    'no-script-url': ERROR,
    'no-self-assign': ERROR,
    'no-self-compare': ERROR,
    'no-sequences': ERROR,
    'no-shadow': WARN,
    'no-shadow-restricted-names': ERROR,
    'no-spaced-func': ERROR,
    'no-sparse-arrays': ERROR,
    'no-sync': OFF,
    'no-tabs': ERROR,
    'no-ternary': OFF,
    'no-template-curly-in-string': WARN,
    'no-throw-literal': ERROR,
    'no-this-before-super': ERROR,
    'no-trailing-spaces': ERROR,
    'no-undef': ERROR,
    'no-undef-init': ERROR,
    'no-undefined': ERROR,
    'no-underscore-dangle': OFF,
    'no-unexpected-multiline': ERROR,
    'no-unmodified-loop-condition': ERROR,
    'no-unneeded-ternary': ERROR,
    'no-unreachable': ERROR,
    'no-unsafe-finally': ERROR,
    'no-unsafe-negation': ERROR,
    'no-unused-expressions': ERROR,
    'no-unused-labels': OFF,
    'no-unused-vars': [ERROR, { args: 'none' }],
    'no-use-before-define': [ERROR, 'nofunc'],
    'no-useless-call': ERROR,
    'no-useless-computed-key': ERROR,
    'no-useless-concat': ERROR,
    'no-useless-constructor': ERROR,
    'no-useless-escape': WARN,
    'no-useless-rename': WARN,
    'no-useless-return': ERROR,
    'no-void': ERROR,
    'no-warning-comments': OFF,
    'no-with': ERROR,
    'no-whitespace-before-property': WARN,
    'nonblock-statement-body-position': OFF,
    'object-curly-newline': OFF,
    'object-curly-spacing': [ERROR, 'always'],
    'object-property-newline': [
      ERROR,
      { allowAllPropertiesOnSameLine: true },
    ],
    'one-var': [ERROR, 'never'],
    'one-var-declaration-per-line': OFF,
    'operator-assignment': [ERROR, 'always'],
    'operator-linebreak': OFF,
    'padded-blocks': OFF,
    'padding-line-between-statements': OFF,
    'prefer-arrow-callback': OFF,
    'prefer-destructuring': OFF,
    'prefer-numeric-literals': ERROR,
    'prefer-object-spread': WARN,
    'prefer-reflect': OFF,
    'prefer-rest-params': WARN,
    'prefer-spread': OFF,
    'prefer-template': OFF,
    'quote-props': [ERROR, 'as-needed'],
    quotes: [ERROR, 'single', { avoidEscape: true }],
    radix: ERROR,
    'require-await': WARN,
    'require-jsdoc': OFF,
    'require-yield': ERROR,
    'rest-spread-spacing': [ERROR, 'never'],
    semi: [ERROR, 'always'],
    'semi-spacing': [ERROR, { before: false, after: true }],
    'semi-style': ERROR,
    'sort-imports': OFF,
    'sort-keys': OFF,
    'sort-vars': OFF,
    'space-after-keywords': OFF,
    'space-before-blocks': [ERROR, 'always'],
    'space-before-function-paren': OFF,
    'keyword-spacing': [
      'error',
      {
        before: true,
      },
    ],
    'space-in-parens': [ERROR, 'never'],
    'space-infix-ops': ERROR,
    'space-unary-ops': ERROR,
    'spaced-comment': [ERROR, 'always'],
    'switch-colon-spacing': WARN,
    'symbol-description': ERROR,
    'template-curly-spacing': [ERROR, 'never'],
    'template-tag-spacing': OFF,
    'unicode-bom': ERROR,
    'valid-jsdoc': ERROR,
    'valid-typeof': ERROR,
    'vars-on-top': ERROR,
    'wrap-iife': ERROR,
    'wrap-regex': OFF,
    yoda: OFF,
  },
};
<commit_msg>style(common): run prettier<commit_after>'use strict';

const OFF = 'off';
const ERROR = 'error';
const WARN = 'warn';

const COMPLEXITY_MAX = 5;
const TABWIDTH = 2;
const NESTED_CALLBACK_MAX = 4;
const ARGUMENTS_MAX = 4;

module.exports = {
  extends: 'eslint:recommended',
  env: {
    node: true,
  },
  globals: {
    require: false,
    module: false,
  },
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'script',
    arrowFunctions: true,
    binaryLiterals: true,
    blockBindings: true,
    classes: false,
    defaultParams: true,
    destructuring: true,
    forOf: true,
    generators: false,
    modules: false,
    objectLiteralComputedProperties: true,
    objectLiteralDuplicateProperties: true,
    objectLiteralShorthandMethods: true,
    objectLiteralShorthandProperties: true,
    octalLiterals: false,
    regexUFlag: true,
    regexYFlag: true,
    restParams: true,
    spread: true,
    superInFunctions: true,
    templateStrings: true,
    unicodeCodePointEscapes: true,
  },
  rules: {
    'accessor-pairs': [ERROR, { getWithoutSet: false, setWithoutGet: true }],
    'array-bracket-newline': OFF,
    'array-bracket-spacing': [ERROR, 'never'],
    'array-callback-return': ERROR,
    'array-element-newline': OFF,
    'arrow-body-style': [ERROR, 'as-needed'],
    'arrow-parens': [ERROR, 'as-needed'],
    'arrow-spacing': ERROR,
    'block-spacing': [ERROR, 'always'],
    'brace-style': OFF,
    'callback-return': [ERROR, ['callback', 'cb', 'next', 'done']],
    camelcase: OFF,
    'capitalized-comments': OFF,
    'class-methods-use-this': ERROR,
    'comma-dangle': [ERROR, 'always-multiline'],
    'comma-spacing': [ERROR, { before: false, after: true }],
    'comma-style': [ERROR, 'last'],
    complexity: [WARN, COMPLEXITY_MAX],
    'computed-property-spacing': [ERROR, 'never'],
    'consistent-return': ERROR,
    'consistent-this': [ERROR, '_this'],
    'constructor-super': ERROR,
    curly: ERROR,
    'default-case': ERROR,
    'dot-location': [ERROR, 'property'],
    'dot-notation': ERROR,
    'eol-last': ERROR,
    eqeqeq: [ERROR, 'smart'],
    'for-direction': ERROR,
    'func-call-spacing': [ERROR, 'never'],
    'func-names': WARN,
    'func-name-matching': OFF,
    'func-style': [ERROR, 'declaration', { allowArrowFunctions: true }],
    'function-paren-newline': OFF,
    'getter-return': ERROR,
    'global-require': ERROR,
    'guard-for-in': ERROR,
    'handle-callback-err': ERROR,
    'id-blacklist': OFF,
    'id-length': OFF,
    'id-match': OFF,
    indent: OFF,
    'init-declarations': OFF,
    'jsx-quotes': OFF,
    'key-spacing': [ERROR, { beforeColon: false, afterColon: true }],
    'lines-between-class-members': OFF,
    'line-comment-position': OFF,
    'linebreak-style': [ERROR, 'unix'],
    'lines-around-comment': OFF,
    'lines-around-directive': OFF,
    'max-len': [
      WARN,
      100,
      TABWIDTH,
      {
        ignoreComments: true,
        ignorePattern: '^\\s*import\\s.+\\sfrom\\s.+;$',
      },
    ],
    'max-classes-per-file': OFF,
    'max-lines': [WARN, { max: 1000 }],
    'max-lines-per-function': OFF,
    'max-nested-callbacks': [ERROR, NESTED_CALLBACK_MAX],
    'max-params': [ERROR, ARGUMENTS_MAX],
    'max-statements-per-line': [WARN, { max: 2 }],
    'multiline-comment-style': OFF,
    'multiline-ternary': OFF,
    'new-cap': [ERROR, { newIsCap: true, capIsNew: true }],
    'new-parens': ERROR,
    'newline-after-var': WARN,
    'newline-before-return': OFF,
    'newline-per-chained-call': OFF,
    'no-alert': ERROR,
    'no-array-constructor': ERROR,
    'no-await-in-loop': OFF,
    'no-buffer-constructor': ERROR,
    'no-caller': ERROR,
    'no-case-declarations': ERROR,
    'no-catch-shadow': ERROR,
    'no-class-assign': ERROR,
    'no-compare-neg-zero': ERROR,
    'no-confusing-arrow': OFF,
    'no-cond-assign': ERROR,
    'no-console': ERROR,
    'no-const-assign': ERROR,
    'no-constant-condition': ERROR,
    'no-continue': OFF,
    'no-control-regex': ERROR,
    'no-debugger': ERROR,
    'no-delete-var': ERROR,
    'no-div-regex': ERROR,
    'no-dupe-args': ERROR,
    'no-dupe-class-members': OFF,
    'no-dupe-keys': ERROR,
    'no-duplicate-case': ERROR,
    'no-duplicate-imports': ERROR,
    'no-else-return': ERROR,
    'no-empty': ERROR,
    'no-empty-character-class': ERROR,
    'no-empty-pattern': ERROR,
    'no-global-assign': ERROR,
    'no-labels': ERROR,
    'no-eq-null': ERROR,
    'no-eval': ERROR,
    'no-ex-assign': ERROR,
    'no-extend-native': ERROR,
    'no-extra-bind': ERROR,
    'no-extra-boolean-cast': ERROR,
    'no-extra-label': OFF,
    'no-extra-parens': OFF,
    'no-extra-semi': ERROR,
    'no-fallthrough': ERROR,
    'no-floating-decimal': ERROR,
    'no-func-assign': ERROR,
    'no-implicit-coercion': OFF,
    'no-implicit-globals': OFF,
    'no-implied-eval': ERROR,
    'no-inline-comments': OFF,
    'no-inner-declarations': ERROR,
    'no-invalid-regexp': ERROR,
    'no-invalid-this': WARN,
    'no-irregular-whitespace': ERROR,
    'no-iterator': ERROR,
    'no-label-var': ERROR,
    'no-lone-blocks': ERROR,
    'no-lonely-if': ERROR,
    'no-loop-func': ERROR,
    'no-magic-numbers': [
      ERROR,
      {
        ignoreArrayIndexes: true,
        ignore: [
          -1,
          0,
          1,
          100,
          101,
          102,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          210,
          226,
          300,
          301,
          302,
          303,
          304,
          305,
          306,
          307,
          308,
          310,
          400,
          401,
          402,
          403,
          404,
          405,
          406,
          407,
          408,
          409,
          410,
          411,
          412,
          413,
          414,
          415,
          416,
          417,
          418,
          421,
          422,
          423,
          424,
          425,
          426,
          427,
          428,
          429,
          431,
          449,
          450,
          451,
          456,
          499,
          500,
          501,
          502,
          503,
          504,
          505,
          506,
          507,
          508,
          509,
          510,
          511,
          520,
        ],
      },
    ],
    'no-mixed-operators': OFF,
    'no-mixed-requires': OFF,
    'no-mixed-spaces-and-tabs': ERROR,
    'no-multi-spaces': ERROR,
    'no-multi-str': ERROR,
    'no-multiple-empty-lines': [ERROR, { max: 2 }],
    'no-native-reassign': ERROR,
    'no-negated-condition': OFF,
    'no-negated-in-lhs': ERROR,
    'no-nested-ternary': OFF,
    'no-new': WARN,
    'no-new-func': ERROR,
    'no-new-object': ERROR,
    'no-new-require': ERROR,
    'no-new-symbol': ERROR,
    'no-obj-calls': ERROR,
    'no-octal': ERROR,
    'no-octal-escape': ERROR,
    'no-param-reassign': OFF,
    'no-path-concat': ERROR,
    'no-process-env': OFF,
    'no-process-exit': OFF,
    'no-proto': ERROR,
    'no-prototype-builtins': WARN,
    'no-redeclare': ERROR,
    'no-regex-spaces': ERROR,
    'no-reserved-keys': OFF,
    'no-restricted-globals': OFF,
    'no-restricted-imports': OFF,
    'no-restricted-modules': OFF,
    'no-restricted-syntax': OFF,
    'no-restricted-properties': [
      ERROR,
      {
        object: 'describe',
        property: 'only',
        message: 'Using describe.only is not allowed',
      },
      {
        object: 'it',
        property: 'only',
        message: 'Using it.only is not allowed',
      },
    ],
    'no-return-assign': ERROR,
    'no-return-await': ERROR,
    'no-script-url': ERROR,
    'no-self-assign': ERROR,
    'no-self-compare': ERROR,
    'no-sequences': ERROR,
    'no-shadow': WARN,
    'no-shadow-restricted-names': ERROR,
    'no-spaced-func': ERROR,
    'no-sparse-arrays': ERROR,
    'no-sync': OFF,
    'no-tabs': ERROR,
    'no-ternary': OFF,
    'no-template-curly-in-string': WARN,
    'no-throw-literal': ERROR,
    'no-this-before-super': ERROR,
    'no-trailing-spaces': ERROR,
    'no-undef': ERROR,
    'no-undef-init': ERROR,
    'no-undefined': ERROR,
    'no-underscore-dangle': OFF,
    'no-unexpected-multiline': ERROR,
    'no-unmodified-loop-condition': ERROR,
    'no-unneeded-ternary': ERROR,
    'no-unreachable': ERROR,
    'no-unsafe-finally': ERROR,
    'no-unsafe-negation': ERROR,
    'no-unused-expressions': ERROR,
    'no-unused-labels': OFF,
    'no-unused-vars': [ERROR, { args: 'none' }],
    'no-use-before-define': [ERROR, 'nofunc'],
    'no-useless-call': ERROR,
    'no-useless-computed-key': ERROR,
    'no-useless-concat': ERROR,
    'no-useless-constructor': ERROR,
    'no-useless-escape': WARN,
    'no-useless-rename': WARN,
    'no-useless-return': ERROR,
    'no-void': ERROR,
    'no-warning-comments': OFF,
    'no-with': ERROR,
    'no-whitespace-before-property': WARN,
    'nonblock-statement-body-position': OFF,
    'object-curly-newline': OFF,
    'object-curly-spacing': [ERROR, 'always'],
    'object-property-newline': [ERROR, { allowAllPropertiesOnSameLine: true }],
    'one-var': [ERROR, 'never'],
    'one-var-declaration-per-line': OFF,
    'operator-assignment': [ERROR, 'always'],
    'operator-linebreak': OFF,
    'padded-blocks': OFF,
    'padding-line-between-statements': OFF,
    'prefer-arrow-callback': OFF,
    'prefer-destructuring': OFF,
    'prefer-numeric-literals': ERROR,
    'prefer-object-spread': WARN,
    'prefer-reflect': OFF,
    'prefer-rest-params': WARN,
    'prefer-spread': OFF,
    'prefer-template': OFF,
    'quote-props': [ERROR, 'as-needed'],
    quotes: [ERROR, 'single', { avoidEscape: true }],
    radix: ERROR,
    'require-await': WARN,
    'require-jsdoc': OFF,
    'require-yield': ERROR,
    'rest-spread-spacing': [ERROR, 'never'],
    semi: [ERROR, 'always'],
    'semi-spacing': [ERROR, { before: false, after: true }],
    'semi-style': ERROR,
    'sort-imports': OFF,
    'sort-keys': OFF,
    'sort-vars': OFF,
    'space-after-keywords': OFF,
    'space-before-blocks': [ERROR, 'always'],
    'space-before-function-paren': OFF,
    'keyword-spacing': [
      'error',
      {
        before: true,
      },
    ],
    'space-in-parens': [ERROR, 'never'],
    'space-infix-ops': ERROR,
    'space-unary-ops': ERROR,
    'spaced-comment': [ERROR, 'always'],
    'switch-colon-spacing': WARN,
    'symbol-description': ERROR,
    'template-curly-spacing': [ERROR, 'never'],
    'template-tag-spacing': OFF,
    'unicode-bom': ERROR,
    'valid-jsdoc': ERROR,
    'valid-typeof': ERROR,
    'vars-on-top': ERROR,
    'wrap-iife': ERROR,
    'wrap-regex': OFF,
    yoda: OFF,
  },
};
<|endoftext|>


<commit_before>'use strict';

function convertID2topic(id, pattern, prefix, namespace) {
    let topic;
    id = (id || '').toString();
    if (pattern && pattern.substring(0, (prefix + namespace).length) === (prefix + namespace)) {
        topic = prefix + id;
    } else if (pattern && pattern.substring(0, namespace.length) === namespace) {
        topic = id;
    } else if (prefix && pattern && pattern.substring(0, prefix.length) === prefix) {
        topic = prefix + id;//.substring(namespace.length + 1);
    } else if (id.substring(0, namespace.length) === namespace) {
        topic = (prefix || '') + id.substring(namespace.length + 1);
    } else {
        topic = (prefix || '') + id;
    }
    topic = topic.replace(/\./g, '/');
    return topic;
}

function state2string(val, sendStateObject) {

    if(typeof sendStateObject === 'undefined' || sendStateObject === null) sendStateObject = false;

    if (val && typeof val === 'object') {
        if (val.ack === undefined && val.val !== undefined) {
            if (val.val === null) return 'null';
            return (sendStateObject === true) ? JSON.stringify(val) : val.val.toString();
        } else {
            return JSON.stringify(val);
        }
    } else {
        return (val === null) ? 'null' : (val === undefined ? 'undefined' : (sendStateObject === true) ? JSON.stringify(val) : val.toString());
    }
}

function convertTopic2id(topic, dontCutNamespace, prefix, namespace) {
    if (!topic) return topic;

    // Remove own prefix if
    if (prefix && topic.substring(0, prefix.length) === prefix) {
        topic = topic.substring(prefix.length);
    }

    topic = topic.replace(/\//g, '.').replace(/\s/g, '_');
    if (topic[0] === '.') topic = topic.substring(1);
    if (topic[topic.length - 1] === '.') topic = topic.substring(0, topic.length - 1);

    if (!dontCutNamespace && topic.substring(0, namespace.length) === namespace) {
        topic = topic.substring(namespace.length + 1);
    }

    return topic;
}

exports.convertTopic2id = convertTopic2id;
exports.convertID2topic = convertID2topic;
exports.state2string    = state2string;
<commit_msg>Fixed return value as either object or plain string<commit_after>'use strict';

function convertID2topic(id, pattern, prefix, namespace) {
    let topic;
    id = (id || '').toString();
    if (pattern && pattern.substring(0, (prefix + namespace).length) === (prefix + namespace)) {
        topic = prefix + id;
    } else if (pattern && pattern.substring(0, namespace.length) === namespace) {
        topic = id;
    } else if (prefix && pattern && pattern.substring(0, prefix.length) === prefix) {
        topic = prefix + id;//.substring(namespace.length + 1);
    } else if (id.substring(0, namespace.length) === namespace) {
        topic = (prefix || '') + id.substring(namespace.length + 1);
    } else {
        topic = (prefix || '') + id;
    }
    topic = topic.replace(/\./g, '/');
    return topic;
}

function state2string(val, sendStateObject) {

    if(typeof sendStateObject === 'undefined' || sendStateObject === null) sendStateObject = false;

    if (val && typeof val === 'object') {
        if (val.val === null) {
            return 'null';
        }
        return (sendStateObject === true) ? JSON.stringify(val) : val.val.toString();
    } else {
        return (val === null) ? 'null' : (val === undefined ? 'undefined' : (sendStateObject === true) ? JSON.stringify(val) : val.toString());
    }
}

function convertTopic2id(topic, dontCutNamespace, prefix, namespace) {
    if (!topic) return topic;

    // Remove own prefix if
    if (prefix && topic.substring(0, prefix.length) === prefix) {
        topic = topic.substring(prefix.length);
    }

    topic = topic.replace(/\//g, '.').replace(/\s/g, '_');
    if (topic[0] === '.') topic = topic.substring(1);
    if (topic[topic.length - 1] === '.') topic = topic.substring(0, topic.length - 1);

    if (!dontCutNamespace && topic.substring(0, namespace.length) === namespace) {
        topic = topic.substring(namespace.length + 1);
    }

    return topic;
}

exports.convertTopic2id = convertTopic2id;
exports.convertID2topic = convertID2topic;
exports.state2string    = state2string;
<|endoftext|>


<commit_before>module.exports = function () {
    return {
        build: {
            files: [
                {
                    expand: true,
                    dot: true,
                    cwd: '<%= src %>',
                    dest: 'build',
                    src: [
                        ''
                    ]
                }
            ]
        }
    }
};<commit_msg>Remove grunt copy dependency<commit_after><|endoftext|>


<commit_before>// external modules
var path = require('path');

// configs
var env = process.env.NODE_ENV || 'development';
var config = require(path.join(__dirname, '..', 'config.json'))[env];
var debug = process.env.DEBUG ? (process.env.DEBUG === 'true') : ((typeof config.debug === 'boolean') ? config.debug : (env === 'development'));

// url
var domain = process.env.DOMAIN || process.env.HMD_DOMAIN || config.domain || '';
var urlpath = process.env.URL_PATH || process.env.HMD_URL_PATH || config.urlpath || '';
var port = process.env.PORT || process.env.HMD_PORT || config.port || 3000;
var alloworigin = process.env.HMD_ALLOW_ORIGIN ? process.env.HMD_ALLOW_ORIGIN.split(',') : (config.alloworigin || ['localhost']);

var usessl = !!config.usessl;
var protocolusessl = (usessl === true && typeof process.env.HMD_PROTOCOL_USESSL === 'undefined' && typeof config.protocolusessl === 'undefined')
     ? true : (process.env.HMD_PROTOCOL_USESSL ? (process.env.HMD_PROTOCOL_USESSL === 'true') : !!config.protocolusessl);
var urladdport = process.env.HMD_URL_ADDPORT ? (process.env.HMD_URL_ADDPORT === 'true') : !!config.urladdport;

var usecdn = process.env.HMD_USECDN ? (process.env.HMD_USECDN === 'true') : ((typeof config.usecdn === 'boolean') ? config.usecdn : true);

var allowanonymous = process.env.HMD_ALLOW_ANONYMOUS ? (process.env.HMD_ALLOW_ANONYMOUS === 'true') : ((typeof config.allowanonymous === 'boolean') ? config.allowanonymous : true);

var allowfreeurl = process.env.HMD_ALLOW_FREEURL ? (process.env.HMD_ALLOW_FREEURL === 'true') : !!config.allowfreeurl;

// db
var dburl = config.dburl || process.env.HMD_DB_URL || process.env.DATABASE_URL;
var db = config.db || {};

// ssl path
var sslkeypath = config.sslkeypath || '';
var sslcertpath = config.sslcertpath || '';
var sslcapath = config.sslcapath || '';
var dhparampath = config.dhparampath || '';

// other path
var tmppath = config.tmppath || './tmp';
var defaultnotepath = config.defaultnotepath || './public/default.md';
var docspath = config.docspath || './public/docs';
var indexpath = config.indexpath || './public/views/index.ejs';
var hackmdpath = config.hackmdpath || './public/views/hackmd.ejs';
var errorpath = config.errorpath || './public/views/error.ejs';
var prettypath = config.prettypath || './public/views/pretty.ejs';
var slidepath = config.slidepath || './public/views/slide.ejs';

// session
var sessionname = config.sessionname || 'connect.sid';
var sessionsecret = config.sessionsecret || 'secret';
var sessionlife = config.sessionlife || 14 * 24 * 60 * 60 * 1000; //14 days

// static files
var staticcachetime = config.staticcachetime || 1 * 24 * 60 * 60 * 1000; // 1 day

// socket.io
var heartbeatinterval = config.heartbeatinterval || 5000;
var heartbeattimeout = config.heartbeattimeout || 10000;

// document
var documentmaxlength = config.documentmaxlength || 100000;

// image upload setting, available options are imgur/s3/filesystem
var imageUploadType = process.env.HMD_IMAGE_UPLOAD_TYPE || config.imageUploadType || 'imgur';

config.s3 = config.s3 || {};
var s3 = {
    accessKeyId: process.env.HMD_S3_ACCESS_KEY_ID || config.s3.accessKeyId,
    secretAccessKey: process.env.HMD_S3_SECRET_ACCESS_KEY || config.s3.secretAccessKey,
    region: process.env.HMD_S3_REGION || config.s3.region
}
var s3bucket = process.env.HMD_S3_BUCKET || config.s3.bucket;

// auth
var facebook = (process.env.HMD_FACEBOOK_CLIENTID && process.env.HMD_FACEBOOK_CLIENTSECRET) ? {
    clientID: process.env.HMD_FACEBOOK_CLIENTID,
    clientSecret: process.env.HMD_FACEBOOK_CLIENTSECRET
} : config.facebook || false;
var twitter = (process.env.HMD_TWITTER_CONSUMERKEY && process.env.HMD_TWITTER_CONSUMERSECRET) ? {
    consumerKey: process.env.HMD_TWITTER_CONSUMERKEY,
    consumerSecret: process.env.HMD_TWITTER_CONSUMERSECRET
} : config.twitter || false;
var github = (process.env.HMD_GITHUB_CLIENTID && process.env.HMD_GITHUB_CLIENTSECRET) ? {
    clientID: process.env.HMD_GITHUB_CLIENTID,
    clientSecret: process.env.HMD_GITHUB_CLIENTSECRET
} : config.github || false;
var gitlab = (process.env.HMD_GITLAB_CLIENTID && process.env.HMD_GITLAB_CLIENTSECRET) ? {
    baseURL: process.env.HMD_GITLAB_BASEURL,
    clientID: process.env.HMD_GITLAB_CLIENTID,
    clientSecret: process.env.HMD_GITLAB_CLIENTSECRET
} : config.gitlab || false;
var dropbox = (process.env.HMD_DROPBOX_CLIENTID && process.env.HMD_DROPBOX_CLIENTSECRET) ? {
    clientID: process.env.HMD_DROPBOX_CLIENTID,
    clientSecret: process.env.HMD_DROPBOX_CLIENTSECRET
} : config.dropbox || false;
var google = (process.env.HMD_GOOGLE_CLIENTID && process.env.HMD_GOOGLE_CLIENTSECRET) ? {
    clientID: process.env.HMD_GOOGLE_CLIENTID,
    clientSecret: process.env.HMD_GOOGLE_CLIENTSECRET
} : config.google || false;
var ldap = config.ldap || (
    process.env.HMD_LDAP_URL ||
    process.env.HMD_LDAP_BINDDN ||
    process.env.HMD_LDAP_BINDCREDENTIALS ||
    process.env.HMD_LDAP_TOKENSECRET ||
    process.env.HMD_LDAP_SEARCHBASE ||
    process.env.HMD_LDAP_SEARCHFILTER ||
    process.env.HMD_LDAP_SEARCHATTRIBUTES ||
    process.env.HMD_LDAP_PROVIDERNAME
) || false;
if (ldap == true)
    ldap = {};
if (process.env.HMD_LDAP_URL)
    ldap.url = process.env.HMD_LDAP_URL;
if (process.env.HMD_LDAP_BINDDN)
    ldap.bindDn = process.env.HMD_LDAP_BINDDN;
if (process.env.HMD_LDAP_BINDCREDENTIALS)
    ldap.bindCredentials = process.env.HMD_LDAP_BINDCREDENTIALS;
if (process.env.HMD_LDAP_TOKENSECRET)
    ldap.tokenSecret = process.env.HMD_LDAP_TOKENSECRET;
if (process.env.HMD_LDAP_SEARCHBASE)
    ldap.searchBase = process.env.HMD_LDAP_SEARCHBASE;
if (process.env.HMD_LDAP_SEARCHFILTER)
    ldap.searchFilter = process.env.HMD_LDAP_SEARCHFILTER;
if (process.env.HMD_LDAP_SEARCHATTRIBUTES)
    ldap.searchAttributes = process.env.HMD_LDAP_SEARCHATTRIBUTES;
if (process.env.HMD_LDAP_TLS_CA) {
    var ca = {
        ca: process.env.HMD_LDAP_TLS_CA
    }
    ldap.tlsOptions = ldap.tlsOptions ? Object.assign(ldap.tlsOptions, ca) : ca
}
if (process.env.HMD_LDAP_PROVIDERNAME) {
    ldap.providerName = process.env.HMD_LDAP_PROVIDERNAME;
}
var imgur = process.env.HMD_IMGUR_CLIENTID || config.imgur || false;
var email = process.env.HMD_EMAIL ? (process.env.HMD_EMAIL === 'true') : !!config.email;
var allowemailregister = process.env.HMD_ALLOW_EMAIL_REGISTER ? (process.env.HMD_ALLOW_EMAIL_REGISTER === 'true') : ((typeof config.allowemailregister === 'boolean') ? config.allowemailregister : true);

function getserverurl() {
    var url = '';
    if (domain) {
        var protocol = protocolusessl ? 'https://' : 'http://';
        url = protocol + domain;
        if (urladdport && ((usessl && port != 443) || (!usessl && port != 80)))
            url += ':' + port;
    }
    if (urlpath)
        url += '/' + urlpath;
    return url;
}

var version = '0.5.0';
var minimumCompatibleVersion = '0.5.0';
var maintenance = true;
var cwd = path.join(__dirname, '..');

module.exports = {
    version: version,
    minimumCompatibleVersion: minimumCompatibleVersion,
    maintenance: maintenance,
    debug: debug,
    urlpath: urlpath,
    port: port,
    alloworigin: alloworigin,
    usessl: usessl,
    serverurl: getserverurl(),
    usecdn: usecdn,
    allowanonymous: allowanonymous,
    allowfreeurl: allowfreeurl,
    dburl: dburl,
    db: db,
    sslkeypath: path.join(cwd, sslkeypath),
    sslcertpath: path.join(cwd, sslcertpath),
    sslcapath: path.join(cwd, sslcapath),
    dhparampath: path.join(cwd, dhparampath),
    tmppath: path.join(cwd, tmppath),
    defaultnotepath: path.join(cwd, defaultnotepath),
    docspath: path.join(cwd, docspath),
    indexpath: path.join(cwd, indexpath),
    hackmdpath: path.join(cwd, hackmdpath),
    errorpath: path.join(cwd, errorpath),
    prettypath: path.join(cwd, prettypath),
    slidepath: path.join(cwd, slidepath),
    sessionname: sessionname,
    sessionsecret: sessionsecret,
    sessionlife: sessionlife,
    staticcachetime: staticcachetime,
    heartbeatinterval: heartbeatinterval,
    heartbeattimeout: heartbeattimeout,
    documentmaxlength: documentmaxlength,
    facebook: facebook,
    twitter: twitter,
    github: github,
    gitlab: gitlab,
    dropbox: dropbox,
    google: google,
    ldap: ldap,
    imgur: imgur,
    email: email,
    allowemailregister: allowemailregister,
    imageUploadType: imageUploadType,
    s3: s3,
    s3bucket: s3bucket
};
<commit_msg>Add basics for secret management by Docker 1.13<commit_after>// external modules
var path = require('path');
var fs = require('fs');

// configs
var env = process.env.NODE_ENV || 'development';
var config = require(path.join(__dirname, '..', 'config.json'))[env];
var debug = process.env.DEBUG ? (process.env.DEBUG === 'true') : ((typeof config.debug === 'boolean') ? config.debug : (env === 'development'));

// Create function that reads docker secrets but fails fast in case of a non docker environment
var handleDockerSecret = fs.existsSync('/run/secrets/') ? function(secret){return fs.existsSync('/run/secrets/' + secret) ? fs.readFileSync('/run/secrets/' + secret) : null;)} : function () {return null}

// url
var domain = process.env.DOMAIN || process.env.HMD_DOMAIN || config.domain || '';
var urlpath = process.env.URL_PATH || process.env.HMD_URL_PATH || config.urlpath || '';
var port = process.env.PORT || process.env.HMD_PORT || config.port || 3000;
var alloworigin = process.env.HMD_ALLOW_ORIGIN ? process.env.HMD_ALLOW_ORIGIN.split(',') : (config.alloworigin || ['localhost']);

var usessl = !!config.usessl;
var protocolusessl = (usessl === true && typeof process.env.HMD_PROTOCOL_USESSL === 'undefined' && typeof config.protocolusessl === 'undefined')
     ? true : (process.env.HMD_PROTOCOL_USESSL ? (process.env.HMD_PROTOCOL_USESSL === 'true') : !!config.protocolusessl);
var urladdport = process.env.HMD_URL_ADDPORT ? (process.env.HMD_URL_ADDPORT === 'true') : !!config.urladdport;

var usecdn = process.env.HMD_USECDN ? (process.env.HMD_USECDN === 'true') : ((typeof config.usecdn === 'boolean') ? config.usecdn : true);

var allowanonymous = process.env.HMD_ALLOW_ANONYMOUS ? (process.env.HMD_ALLOW_ANONYMOUS === 'true') : ((typeof config.allowanonymous === 'boolean') ? config.allowanonymous : true);

var allowfreeurl = process.env.HMD_ALLOW_FREEURL ? (process.env.HMD_ALLOW_FREEURL === 'true') : !!config.allowfreeurl;

// db
var dburl = config.dburl || process.env.HMD_DB_URL || process.env.DATABASE_URL;
var db = config.db || {};

// ssl path
var sslkeypath = (fs.existsSync('/run/secrets/key.pem') ? '/run/secrets/key.pem' : null) || config.sslkeypath || '';
var sslcertpath = (fs.existsSync('/run/secrets/cert.pem') ? '/run/secrets/cert.pem' : null) || config.sslcertpath || '';
var sslcapath = (fs.existsSync('/run/secrets/ca.pem') ? '/run/secrets/ca.pem' : null) || config.sslcapath || '';
var dhparampath = (fs.existsSync('/run/secrets/dhparam.pem') ? '/run/secrets/dhparam.pem' : null) || config.dhparampath || '';

// other path
var tmppath = config.tmppath || './tmp';
var defaultnotepath = config.defaultnotepath || './public/default.md';
var docspath = config.docspath || './public/docs';
var indexpath = config.indexpath || './public/views/index.ejs';
var hackmdpath = config.hackmdpath || './public/views/hackmd.ejs';
var errorpath = config.errorpath || './public/views/error.ejs';
var prettypath = config.prettypath || './public/views/pretty.ejs';
var slidepath = config.slidepath || './public/views/slide.ejs';

// session
var sessionname = config.sessionname || 'connect.sid';
var sessionsecret = handleDockerSecret('sessionsecret') || config.sessionsecret || 'secret';
var sessionlife = config.sessionlife || 14 * 24 * 60 * 60 * 1000; //14 days

// static files
var staticcachetime = config.staticcachetime || 1 * 24 * 60 * 60 * 1000; // 1 day

// socket.io
var heartbeatinterval = config.heartbeatinterval || 5000;
var heartbeattimeout = config.heartbeattimeout || 10000;

// document
var documentmaxlength = config.documentmaxlength || 100000;

// image upload setting, available options are imgur/s3/filesystem
var imageUploadType = process.env.HMD_IMAGE_UPLOAD_TYPE || config.imageUploadType || 'imgur';

config.s3 = config.s3 || {};
var s3 = {
    accessKeyId: handleDockerSecret('s3_acccessKeyId') || process.env.HMD_S3_ACCESS_KEY_ID || config.s3.accessKeyId,
    secretAccessKey: handleDockerSecret('s3_secretAccessKey') || process.env.HMD_S3_SECRET_ACCESS_KEY || config.s3.secretAccessKey,
    region: process.env.HMD_S3_REGION || config.s3.region
}
var s3bucket = process.env.HMD_S3_BUCKET || config.s3.bucket;

// auth
var facebook = (process.env.HMD_FACEBOOK_CLIENTID && process.env.HMD_FACEBOOK_CLIENTSECRET || fs.existsSync('/run/secrets/facebook_clientID') && fs.existsSync('/run/secrets/facebook_clientSecret')) ? {
    clientID: handleDockerSecret('facebook_clientID') || process.env.HMD_FACEBOOK_CLIENTID,
    clientSecret: handleDockerSecret('facebook_clientSecret') || process.env.HMD_FACEBOOK_CLIENTSECRET
} : config.facebook || false;
var twitter = (process.env.HMD_TWITTER_CONSUMERKEY && process.env.HMD_TWITTER_CONSUMERSECRET || fs.existsSync('/run/secrets/twitter_consumerKey') && fs.existsSync('/run/secrets/twitter_consumerSecret')) ? {
    consumerKey: handleDockerSecret('twitter_consumerKey') || process.env.HMD_TWITTER_CONSUMERKEY,
    consumerSecret: handleDockerSecret('twitter_consumerSecret') || process.env.HMD_TWITTER_CONSUMERSECRET
} : config.twitter || false;
var github = (process.env.HMD_GITHUB_CLIENTID && process.env.HMD_GITHUB_CLIENTSECRET || fs.existsSync('/run/secrets/github_clientID') && fs.existsSync('/run/secrets/github_clientSecret')) ? {
    clientID: handleDockerSecret('github_clientID') || process.env.HMD_GITHUB_CLIENTID,
    clientSecret: handleDockerSecret('github_clientSecret') || process.env.HMD_GITHUB_CLIENTSECRET
} : config.github || false;
var gitlab = (process.env.HMD_GITLAB_CLIENTID && process.env.HMD_GITLAB_CLIENTSECRET || fs.existsSync('/run/secrets/gitlab_clientID') && fs.existsSync('/run/secrets/gitlab_clientSecret')) ? {
    baseURL: process.env.HMD_GITLAB_BASEURL,
    clientID: handleDockerSecret('gitlab_clientID') || process.env.HMD_GITLAB_CLIENTID,
    clientSecret: handleDockerSecret('gitlab_clientSecret') || process.env.HMD_GITLAB_CLIENTSECRET
} : config.gitlab || false;
var dropbox = (process.env.HMD_DROPBOX_CLIENTID && process.env.HMD_DROPBOX_CLIENTSECRET || fs.existsSync('/run/secrets/dropbox_clientID') && fs.existsSync('/run/secrets/dropbox_clientSecret')) ? {
    clientID: handleDockerSecret('dropbox_clientID') || process.env.HMD_DROPBOX_CLIENTID,
    clientSecret: handleDockerSecret('dropbox_clientSecret') || process.env.HMD_DROPBOX_CLIENTSECRET
} : config.dropbox || false;
var google = (process.env.HMD_GOOGLE_CLIENTID && process.env.HMD_GOOGLE_CLIENTSECRET || fs.existsSync('/run/secrets/google_clientID') && fs.existsSync('/run/secrets/google_clientSecret')) ? {
    clientID: process.env.HMD_GOOGLE_CLIENTID,
    clientSecret: process.env.HMD_GOOGLE_CLIENTSECRET
} : config.google || false;
var ldap = config.ldap || (
    process.env.HMD_LDAP_URL ||
    process.env.HMD_LDAP_BINDDN ||
    process.env.HMD_LDAP_BINDCREDENTIALS ||
    process.env.HMD_LDAP_TOKENSECRET ||
    process.env.HMD_LDAP_SEARCHBASE ||
    process.env.HMD_LDAP_SEARCHFILTER ||
    process.env.HMD_LDAP_SEARCHATTRIBUTES ||
    process.env.HMD_LDAP_PROVIDERNAME
) || false;
if (ldap == true)
    ldap = {};
if (process.env.HMD_LDAP_URL)
    ldap.url = process.env.HMD_LDAP_URL;
if (process.env.HMD_LDAP_BINDDN)
    ldap.bindDn = process.env.HMD_LDAP_BINDDN;
if (process.env.HMD_LDAP_BINDCREDENTIALS)
    ldap.bindCredentials = process.env.HMD_LDAP_BINDCREDENTIALS;
if (process.env.HMD_LDAP_TOKENSECRET)
    ldap.tokenSecret = process.env.HMD_LDAP_TOKENSECRET;
if (process.env.HMD_LDAP_SEARCHBASE)
    ldap.searchBase = process.env.HMD_LDAP_SEARCHBASE;
if (process.env.HMD_LDAP_SEARCHFILTER)
    ldap.searchFilter = process.env.HMD_LDAP_SEARCHFILTER;
if (process.env.HMD_LDAP_SEARCHATTRIBUTES)
    ldap.searchAttributes = process.env.HMD_LDAP_SEARCHATTRIBUTES;
if (process.env.HMD_LDAP_TLS_CA) {
    var ca = {
        ca: process.env.HMD_LDAP_TLS_CA
    }
    ldap.tlsOptions = ldap.tlsOptions ? Object.assign(ldap.tlsOptions, ca) : ca
}
if (process.env.HMD_LDAP_PROVIDERNAME) {
    ldap.providerName = process.env.HMD_LDAP_PROVIDERNAME;
}
var imgur = handleDockerSecret('imgur_clientid') || process.env.HMD_IMGUR_CLIENTID || config.imgur || false;
var email = process.env.HMD_EMAIL ? (process.env.HMD_EMAIL === 'true') : !!config.email;
var allowemailregister = process.env.HMD_ALLOW_EMAIL_REGISTER ? (process.env.HMD_ALLOW_EMAIL_REGISTER === 'true') : ((typeof config.allowemailregister === 'boolean') ? config.allowemailregister : true);

function getserverurl() {
    var url = '';
    if (domain) {
        var protocol = protocolusessl ? 'https://' : 'http://';
        url = protocol + domain;
        if (urladdport && ((usessl && port != 443) || (!usessl && port != 80)))
            url += ':' + port;
    }
    if (urlpath)
        url += '/' + urlpath;
    return url;
}

var version = '0.5.0';
var minimumCompatibleVersion = '0.5.0';
var maintenance = true;
var cwd = path.join(__dirname, '..');

module.exports = {
    version: version,
    minimumCompatibleVersion: minimumCompatibleVersion,
    maintenance: maintenance,
    debug: debug,
    urlpath: urlpath,
    port: port,
    alloworigin: alloworigin,
    usessl: usessl,
    serverurl: getserverurl(),
    usecdn: usecdn,
    allowanonymous: allowanonymous,
    allowfreeurl: allowfreeurl,
    dburl: dburl,
    db: db,
    sslkeypath: path.join(cwd, sslkeypath),
    sslcertpath: path.join(cwd, sslcertpath),
    sslcapath: path.join(cwd, sslcapath),
    dhparampath: path.join(cwd, dhparampath),
    tmppath: path.join(cwd, tmppath),
    defaultnotepath: path.join(cwd, defaultnotepath),
    docspath: path.join(cwd, docspath),
    indexpath: path.join(cwd, indexpath),
    hackmdpath: path.join(cwd, hackmdpath),
    errorpath: path.join(cwd, errorpath),
    prettypath: path.join(cwd, prettypath),
    slidepath: path.join(cwd, slidepath),
    sessionname: sessionname,
    sessionsecret: sessionsecret,
    sessionlife: sessionlife,
    staticcachetime: staticcachetime,
    heartbeatinterval: heartbeatinterval,
    heartbeattimeout: heartbeattimeout,
    documentmaxlength: documentmaxlength,
    facebook: facebook,
    twitter: twitter,
    github: github,
    gitlab: gitlab,
    dropbox: dropbox,
    google: google,
    ldap: ldap,
    imgur: imgur,
    email: email,
    allowemailregister: allowemailregister,
    imageUploadType: imageUploadType,
    s3: s3,
    s3bucket: s3bucket
};
<|endoftext|>


<commit_before>/**
 * Configuration defaults
 */

class Config {
  constructor(options = {}) {
    this.blockLimit = 6718946;
    this.defaultGasPrice = 5;

    this.currency = options.currency || "eur";
    this.ethPrice = options.ethPrice || null;
    this.gasPrice = options.gasPrice || null;
    this.outputFile = options.outputFile || null;
    this.rst = options.rst || false;
    this.rstTitle = options.rstTitle || "";
    this.showTimeSpent = options.showTimeSpent || false;
    this.srcPath = options.src || "contracts";
    this.artifactType = options.artifactType || "truffle-v5";
    this.noColors = options.noColors;
    this.proxyResolver = options.proxyResolver || null;

    this.excludeContracts = Array.isArray(options.excludeContracts)
      ? options.excludeContracts
      : [];

    this.onlyCalledMethods = options.onlyCalledMethods === false ? false : true;

    this.url = options.url || this.resolveClientUrl(options);
  }

  /**
   * Tries to obtain the client url reporter's sync-requests will
   * target. If url is ws://, http:// must be substituted.
   * @param  {Object} options mocha's reporterOptions
   * @return {String}         url e.g http://localhost:8545
   */
  resolveClientUrl(options) {
    // Case: web3 globally available in mocha test context
    try {
      if (web3 && web3.currentProvider) {
        const cp = web3.currentProvider;

        // Truffle/Web3 http
        if (cp.host) return cp.host;

        // Truffle/Web3 websockets
        if (cp.connection) return cp.connection.url.replace("ws://", "http://");

        // Buildler web3 plugin
        // Per #116 another possibility is
        // `config.networks[buidlerArguments.network].url`
        if (cp._provider && cp._provider.provider && cp._provider.provider.host)
          return cp._provider.provider.host;
      }
    } catch (err) {
      // Web3 undefined
    }

    // Case: Failure
    const msg =
      `ERROR: eth-gas-reporter was unable to resolve a client url ` +
      `from the provider available in your test context. Try setting the ` +
      `url as a mocha reporter option (ex: url='http://localhost:8545')`;

    log(message);
    process.exit(1);
  }
}

module.exports = Config;
<commit_msg>Fix missing codechecks in config<commit_after>/**
 * Configuration defaults
 */

class Config {
  constructor(options = {}) {
    this.blockLimit = 6718946;
    this.defaultGasPrice = 5;

    this.currency = options.currency || "eur";
    this.ethPrice = options.ethPrice || null;
    this.gasPrice = options.gasPrice || null;
    this.outputFile = options.outputFile || null;
    this.rst = options.rst || false;
    this.rstTitle = options.rstTitle || "";
    this.showTimeSpent = options.showTimeSpent || false;
    this.srcPath = options.src || "contracts";
    this.artifactType = options.artifactType || "truffle-v5";
    this.noColors = options.noColors;
    this.proxyResolver = options.proxyResolver || null;
    this.codechecks = options.codechecks || false;

    this.excludeContracts = Array.isArray(options.excludeContracts)
      ? options.excludeContracts
      : [];

    this.onlyCalledMethods = options.onlyCalledMethods === false ? false : true;

    this.url = options.url || this.resolveClientUrl(options);
  }

  /**
   * Tries to obtain the client url reporter's sync-requests will
   * target. If url is ws://, http:// must be substituted.
   * @param  {Object} options mocha's reporterOptions
   * @return {String}         url e.g http://localhost:8545
   */
  resolveClientUrl(options) {
    // Case: web3 globally available in mocha test context
    try {
      if (web3 && web3.currentProvider) {
        const cp = web3.currentProvider;

        // Truffle/Web3 http
        if (cp.host) return cp.host;

        // Truffle/Web3 websockets
        if (cp.connection) return cp.connection.url.replace("ws://", "http://");

        // Buildler web3 plugin
        // Per #116 another possibility is
        // `config.networks[buidlerArguments.network].url`
        if (cp._provider && cp._provider.provider && cp._provider.provider.host)
          return cp._provider.provider.host;
      }
    } catch (err) {
      // Web3 undefined
    }

    // Case: Failure
    const msg =
      `ERROR: eth-gas-reporter was unable to resolve a client url ` +
      `from the provider available in your test context. Try setting the ` +
      `url as a mocha reporter option (ex: url='http://localhost:8545')`;

    log(message);
    process.exit(1);
  }
}

module.exports = Config;
<|endoftext|>


<commit_before>var fs = require('fs')
var repeatString = require('repeat-string')
var editorconfigIndent = require('editorconfig-indent')
var editorconfig = fs.readFileSync(process.cwd() + '/.editorconfig', 'utf-8')
var ec = editorconfigIndent(editorconfig)

if (ec.indentStyle === 'tab') {
  indentWidth = '	'
}
else if (ec.indentStyle === 'space' || ec.indentStyle === null) {
  indentWidth = repeatString(' ', ec.indentSize)
}

module.exports = {
  indentWidth: indentWidth
}
<commit_msg>fix #32<commit_after>var fs = require('fs')
var repeatString = require('repeat-string')
var editorconfigIndent = require('editorconfig-indent')

var editorconfig
var ec

try {
  editorconfig = fs.readFileSync(process.cwd() + '/.editorconfig', 'utf-8')
  ec = editorconfigIndent(editorconfig)
} catch (e) {}

if (ec) {
  if (ec.indentStyle === 'tab') {
    indentWidth = '	'
  }
  else if (ec.indentStyle === 'space' || ec.indentStyle === null) {
    indentWidth = repeatString(' ', ec.indentSize)
  }
}
else {
  indentWidth = '  '
}

module.exports = {
  indentWidth: indentWidth
}
<|endoftext|>


<commit_before>var fs = require('fs-extra')
var _ = require('lodash-node/modern')

var defaultConfig = {

  // build options
  source: '.',
  destination: '_site',
  excludeFiles: [],
  includeFiles: [], // e.g. .htaccess

  // environment options
  env: 'production',

  // template options
  partialPath: '_partials',

  // plugin options
  pluginPath: '_plugins',
  excludePlugins: [],

  // post options
  postTypes: ['post'],
  excerptLength: 40,

  // page options
  permalink: '/:title',

  // taxonomy options
  taxonomyTypes: [],

  // serve options
  port: 4000,
  watch: false,
  watchExcludes: []
}

// if no config file exists, just use an empty object
var userConfig = fs.existsSync('_config.json')
  ? fs.readJSONSync('_config.json')
  : {}

module.exports = Object.create(null, {

  init: {
    value: function(commandLineOptions) {

      // enforce Object.freeze()
      // semicolon needed for stupid jshint
      'use strict';

      _.assign(this, defaultConfig, userConfig, commandLineOptions)

      // make sure certain files are always excluded
      this.excludeFiles = _.union(
        this.excludeFiles,
        ['_*', '_*/**/*', 'package.json', 'node_modules/**/*']
      )

      // make sure certain directories are never watched
      this.watchExcludes = _.union(
        this.watchExcludes,
        ['node_modules', this.destination]
      )

      // prevent any future modifications
      Object.freeze(this)
    }
  }

})
<commit_msg>Fix a few typos in the config module.<commit_after>var fs = require('fs-extra')
var _ = require('lodash-node/modern')

var defaultConfig = {

  // build options
  source: '.',
  destination: '_site',
  excludeFiles: [],
  includeFiles: [], // e.g. .htaccess

  // environment options
  env: 'production',

  // template options
  partialsDirectory: '_partials',

  // plugin options
  pluginDirectory: '_plugins',
  excludePlugins: [],

  // post options
  postTypes: ['post'],
  excerptLength: 40,

  // page options
  permalink: '/:title',

  // taxonomy options
  taxonomyTypes: [],

  // serve options
  port: 4000,
  watch: false,
  watchExcludes: []
}

// if no config file exists, just use an empty object
var userConfig = fs.existsSync('_config.json')
  ? fs.readJSONSync('_config.json')
  : {}

module.exports = Object.create(null, {

  init: {
    value: function(commandLineOptions) {

      // enforce Object.freeze()
      // semicolon needed for stupid jshint
      'use strict';

      _.assign(this, defaultConfig, userConfig, commandLineOptions)

      // make sure certain files are always excluded
      this.excludeFiles = _.union(
        this.excludeFiles,
        ['_*', '_*/**/*', 'package.json', 'node_modules/**/*']
      )

      // make sure certain directories are never watched
      this.watchExcludes = _.union(
        this.watchExcludes,
        ['node_modules', this.destination]
      )

      // prevent any future modifications
      Object.freeze(this)
    }
  }

})
<|endoftext|>