<commit_before>module.exports = (function(){
    "use strict";

    var mongoose = require('mongoose'),
        _ = require('underscore'),
        Schema = mongoose.Schema,
        schema = new Schema({
            label : { type: String, required : true, trim: true },
            description : { type : String },
            helpText: { type : String },
            fields: { type: Schema.Types.Mixed, required: true }
        });

    /**
     * A field is valid if:
     * 1) The passed in argument must be an instance of an object
     * 2) All of the mandatory properties are provided
     * 3) The id property cannot have any spaces
     * 4) The type property must be in the approved list
     * 5) The required property must be a boolean
     * @param obj
     * @returns {null}
     */
    function isValidField(key, obj){
        var err = null,
            props = Object.keys(obj),
            mandatoryProps = [
                'label',
                'type',
                'min',
                'max',
                'required',

            ];

        if(!(obj instanceof Object)){
            err = new Error("Fields must be an instance of an object");
        }
        else {

            for(var x = 0; x < mandatoryProps.length; x++){
                var prop = mandatoryProps[x];

                if(!_.contains(props, prop)){
                    err = new Error("'" + prop + "' property not found when validating the content type.");
                }
            }

            if(!err && key.indexOf(' ') >= 0){
                err = new Error("ids for fields cannot have any spaces.");
            }

            if(!err && (typeof obj.required != "boolean")){
                err = new Error("'required' field value should be a boolean.");
            }

            if(!err && !_.isNumber(obj.min) || !_.isNumber(obj.max)){
                err = new Error("'max / min' field value should be a number.");
            }

            if(!err && !_.isBoolean(obj.useAsLabel)){
                err = new Error("'useAsLabel' field value should be a boolean.");
            }

        }

        return err;
    }

    /**
     * In order to be valid we are checking the following rules
     * 1) Collection must be an instance of an array
     * 2) Does the element in the Collection array have all of the necessary properties
     * 3) Are there any duplicate ids
     *
     * @param collection
     * @returns {null}
     */
    function validateFieldType(value){
        var err = null;

        for(var key in value){
            err = isValidField(key, value[key]);
        }

        if(!_.findWhere(value, { useAsLabel : true })) {
            err = 'At least one field must be marked, Use As Label';
        }

        return (err == null);
    }

    schema.path('fields').validate(function(value){
        return validateFieldType(value);
    }, "Invalid Field Object");

    return schema;
})();<commit_msg>Content Type will now validate boolean on the the useAsLabel field.<commit_after>module.exports = (function(){
    "use strict";

    var mongoose = require('mongoose'),
        _ = require('underscore'),
        Schema = mongoose.Schema,
        schema = new Schema({
            label : { type: String, required : true, trim: true },
            description : { type : String },
            helpText: { type : String },
            fields: { type: Schema.Types.Mixed, required: true }
        });

    /**
     * A field is valid if:
     * 1) The passed in argument must be an instance of an object
     * 2) All of the mandatory properties are provided
     * 3) The id property cannot have any spaces
     * 4) The type property must be in the approved list
     * 5) The required property must be a boolean
     * @param obj
     * @returns {null}
     */
    function isValidField(key, obj){
        var err = null,
            props = Object.keys(obj),
            mandatoryProps = [
                'label',
                'type',
                'min',
                'max',
                'required',

            ];

        if(!(obj instanceof Object)){
            err = new Error("Fields must be an instance of an object");
        }
        else {

            for(var x = 0; x < mandatoryProps.length; x++){
                var prop = mandatoryProps[x];

                if(!_.contains(props, prop)){
                    err = new Error("'" + prop + "' property not found when validating the content type.");
                }
            }

            if(!err && key.indexOf(' ') >= 0){
                err = new Error("ids for fields cannot have any spaces.");
            }

            if(!err && (typeof obj.required != "boolean")){
                err = new Error("'required' field value should be a boolean.");
            }

            if(!err && !_.isNumber(obj.min) || !_.isNumber(obj.max)){
                err = new Error("'max / min' field value should be a number.");
            }

            if(!err && !_.isBoolean(obj.useAsLabel)){
                err = new Error("'useAsLabel' field value should be a boolean.");
            }

        }

        return err;
    }

    /**
     * In order to be valid we are checking the following rules
     * 1) Collection must be an instance of an array
     * 2) Does the element in the Collection array have all of the necessary properties
     * 3) Are there any duplicate ids
     *
     * @param collection
     * @returns {null}
     */
    function validateFieldType(value){
        var err = null;

        for(var key in value){
            err = isValidField(key, value[key]);
        }

        if(!_.findWhere(value, { useAsLabel : true })) {
            err = 'At least one field must be marked, Use As Label';
        }

        return (err == null);
    }

    schema.path('fields').validate(function(value){
        return validateFieldType(value);
    }, "Invalid Field Object");

    return schema;
})();<|endoftext|>


<commit_before>import path                           from 'path'
import webpack                        from 'webpack'
import baseConfig                     from './webpack.base.conf.babel'
import HtmlWebpackPlugin              from 'html-webpack-plugin'
import merge                          from 'webpack-merge'
import OptimizeCssAssetsPlugin        from 'optimize-css-assets-webpack-plugin'

baseConfig.entry = {}

let appProdConfig = {
  // whether to generate source map for production files.
  // disabling this can speed up the build.
  devtool: false, // '#source-map',

  entry: {
    app: [
        'babel-polyfill',
        './src/renderer/index.jsx'
    ]
  },

  output: {
    filename: '[name].[chunkhash:8].js',
    chunkFilename: '[id].js',
    path: path.resolve(__dirname, '../app/dist'),
    publicPath: './'
  },

  module: {
    rules: [
      {
        test: /\.jsx$/,
        loader: 'babel-loader?presets[]=react&presets[]=es2015&presets[]=es2017&presets[]=stage-2',
        exclude: /node_modules/
      }
    ]
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    new OptimizeCssAssetsPlugin({
      assetNameRegExp: /\.min\.css$/g,
      cssProcessor: require('cssnano'),
      cssProcessorOptions: { discardComments: {removeAll: true } },
      canPrint: true
    }),
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: '../../app/dist/index.html',
      template: 'src/renderer/index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      bodyClass: `platform_${process.platform}`
    })
  ]
}

let electronProdConfig = {
  // whether to generate source map for production files.
  // disabling this can speed up the build.
  devtool: false, // '#source-map',

  entry: {
    electron: [
        'babel-polyfill',
        './src/main/index.js'
    ]
  },

  output: {
    filename: '[name].js', // for Electron, the main entry name is fixed in package.json, hash should removed
    chunkFilename: '[id].js',
    path: path.resolve(__dirname, '../app/dist'),
    publicPath: './'
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
  ]
}

export default [
  merge(baseConfig, appProdConfig),
  merge(baseConfig, electronProdConfig)
]
<commit_msg>解决webpack压缩混淆js导致rxSchema不正确的问题<commit_after>import path                           from 'path'
import webpack                        from 'webpack'
import baseConfig                     from './webpack.base.conf.babel'
import HtmlWebpackPlugin              from 'html-webpack-plugin'
import merge                          from 'webpack-merge'
import OptimizeCssAssetsPlugin        from 'optimize-css-assets-webpack-plugin'

baseConfig.entry = {}

let appProdConfig = {
  // whether to generate source map for production files.
  // disabling this can speed up the build.
  devtool: false, // '#source-map',

  entry: {
    app: [
        'babel-polyfill',
        './src/renderer/index.jsx'
    ]
  },

  output: {
    filename: '[name].[chunkhash:8].js',
    chunkFilename: '[id].js',
    path: path.resolve(__dirname, '../app/dist'),
    publicPath: './'
  },

  module: {
    rules: [
      {
        test: /\.jsx$/,
        loader: 'babel-loader?presets[]=react&presets[]=es2015&presets[]=es2017&presets[]=stage-2',
        exclude: /node_modules/
      }
    ]
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      mangle: {
        except: ['exports', 'require', 'RxSchema', 'RxDatabase']
      },
      sourceMap: false
    }),
    new OptimizeCssAssetsPlugin({
      assetNameRegExp: /\.min\.css$/g,
      cssProcessor: require('cssnano'),
      cssProcessorOptions: { discardComments: {removeAll: true } },
      canPrint: true
    }),
    // see https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: '../../app/dist/index.html',
      template: 'src/renderer/index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      bodyClass: `platform_${process.platform}`
    })
  ]
}

let electronProdConfig = {
  // whether to generate source map for production files.
  // disabling this can speed up the build.
  devtool: false, // '#source-map',

  entry: {
    electron: [
        'babel-polyfill',
        './src/main/index.js'
    ]
  },

  output: {
    filename: '[name].js', // for Electron, the main entry name is fixed in package.json, hash should removed
    chunkFilename: '[id].js',
    path: path.resolve(__dirname, '../app/dist'),
    publicPath: './'
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
  ]
}

export default [
  merge(baseConfig, appProdConfig),
  merge(baseConfig, electronProdConfig)
]
<|endoftext|>


<commit_before>console.log("ui.js loaded");

var c;
var g;
var wid,hei;
var map;
var best;

var upArrowDown;
var rightArrowDown;
var leftArrowDown;
var mainPwr,sidePwr;

function init(){
	console.log("initialising");
	if(!navigator.cookieEnabled || document.cookie.search("best=")==-1){
		best=0;
	}
	else{
		var str=document.cookie.toString();
		best=Number(str.substring(5));
	}

	wid=500;
	hei=500;
	map=new Map(wid,hei);
	mainPwr=0;
	sidePwr=0;
	upArrowDown=false;
	rightArrowDown=false;
	leftArrowDown=false;
	c= document.getElementById("canvas0");
	c.addEventListener("click",click);
	var body=document.getElementById("body");
	body.addEventListener("keyup",keyUp);
	body.addEventListener("keydown",keyDown);
	g=c.getContext("2d");
	updateAll();
	draw();
	//setInterval("rotater()",25);
	setInterval("gameLoop()",100);
}

function draw(){
	//draw background
	g.fillStyle = "#FFFFFF";
	g.fillRect(0,0,wid,hei);
	if(map.alive){
		//draw ship
		g.fillStyle = "#FF0000";
		g.beginPath();
		g.moveTo(map.ship.vertices[0].x,map.ship.vertices[0].y);
		for(var i=1;i<5;i++) g.lineTo(map.ship.vertices[i].x,map.ship.vertices[i].y);
		g.closePath();
		g.fill();
		//draw flames
		//main
		g.fillStyle = "#ff6400";
		g.beginPath();
		g.moveTo(map.ship.mainFlame[0].x,map.ship.mainFlame[0].y);
		for(var i=1;i<3;i++) g.lineTo(map.ship.mainFlame[i].x,map.ship.mainFlame[i].y);
		g.closePath();
		g.fill();
		//side
		g.beginPath();
		g.moveTo(map.ship.sideFlame[0].x,map.ship.sideFlame[0].y);
		for(var i=1;i<3;i++) g.lineTo(map.ship.sideFlame[i].x,map.ship.sideFlame[i].y);
		g.closePath();
		g.fill();
		//draw asteroids
		g.fillStyle="#642010"
		for(var i=0;i<map.asteroids.length;i++){
			var s=map.asteroids[i].shape;
			g.beginPath();
			g.arc(s.center.x,s.center.y,s.radius,0,2*Math.PI);
			g.fill();
		}
		//draw score
		g.fillStyle = "#000000";
		g.font="bold 16px Courier New";
		g.textBaseline="top";
		g.textAlign="left";
		g.fillText("score: "+map.score,5,0);
		g.fillText("best : "+best,5,20);
		//draw power meters
		g.fillStyle="#999999";
		g.fillRect(410,470,80,20);
		g.fillRect(440,380,20,80);
		g.strokeStyle= "#000000";
		g.lineWidth=(3);
		g.strokeRect(410,470,80,20);
		g.strokeRect(440,380,20,80);
		g.beginPath();
		g.moveTo(450,470);
		g.lineTo(450,490);
		g.stroke();
		//fill in power meters
		g.fillStyle="#FF0000";
		g.fillRect(440,380,20,mainPwr*8);
		if(sidePwr>=0)g.fillRect(450,470,sidePwr*4,20);
		else g.fillRect(450+sidePwr*4,470,sidePwr*-4,20);
	}
	else{
		//game over screen
		g.fillStyle = "#000000";
		g.font="bold 42px Courier New";
		g.textBaseline="center";
		g.textAlign="center";
		g.fillText("GAME OVER!",wid/2,hei/2);
		g.font="bold 20px Courier New";
		g.fillText("score: "+map.score,wid/2,hei/2+40);
		g.fillText("best : "+best,wid/2,hei/2+65);
		g.fillText("Click to start again!",wid/2,hei-40);
	}
}

function updateMainFlame(){
	with(obrengine){
		var forward=scaleVector(getUnitVector(map.ship.angle),map.ship.len/2);
		var side=scaleVector(getUnitVector(map.ship.angle+Math.PI/2),map.ship.wid/2);
		map.ship.mainFlame=[
			subtractVectors(map.ship.pos,addVectors(forward,side)),
			addVectors(map.ship.pos,subtractVectors(side,forward)),
			subtractVectors(map.ship.pos,scaleVector(forward,1+map.ship.pwr*2)),
		];
	}
}

function updateSideFlame(){
	with(obrengine){
		var forward=scaleVector(getUnitVector(map.ship.angle),map.ship.len/2);
		var side=scaleVector(getUnitVector(map.ship.angle+Math.PI/2),map.ship.wid/2);
		if(sidePwr>=0){
			map.ship.sideFlame=[
			addVectors(map.ship.pos,subtractVectors(forward,side)),
			addVectors(map.ship.pos,subtractVectors(scaleVector(forward,0.8),scaleVector(side,1+map.ship.sidePwr))),
			addVectors(map.ship.pos,subtractVectors(scaleVector(forward,0.6),side)),
			];
		}
		else{
			map.ship.sideFlame=[
			addVectors(map.ship.pos,addVectors(forward,side)),
			addVectors(map.ship.pos,addVectors(scaleVector(forward,0.8),scaleVector(side,1-map.ship.sidePwr))),
			addVectors(map.ship.pos,addVectors(scaleVector(forward,0.6),side)),
			];
		}
	}
}

function updateAll(){
	map.ship.updateVertices();
	updateMainFlame();
	updateSideFlame();
}

/* function rotater(){
	ship.angle+=0.05;
	ship.updateVertices();
	draw();
} */

function keyDown(e){
	////console.log("key down. code="+e.keyCode);
	//left arrow: -ve side thrust
	if(e.keyCode==37){
		leftArrowDown=true;
		if(sidePwr>0) sidePwr=0;
	}
	//up arrow
	else if(e.keyCode==38){
		upArrowDown=true;
	}
	//right arrow: +ve side thrust
	else if(e.keyCode==39){
		rightArrowDown=true;
		if(sidePwr<0) sidePwr=0;
	}
	//down arrow
	else if(e.keyCode==40){
		mainPwr=0;
	}
}

function keyUp(e){
	////console.log("key up. code="+e.keyCode);
	//left arrow: -ve side thrust
	if(e.keyCode==37){
		leftArrowDown=false;
	}
	//up arrow
	else if(e.keyCode==38){
		upArrowDown=false;
	}
	//right arrow: +ve side thrust
	else if(e.keyCode==39){
		rightArrowDown=false;
	}
	//down arrow
	else if(e.keyCode==40){

	}
}

function click(){
	console.log("clicked");
	if(!map.alive){
		map=new Map(wid,hei);
		mainPwr=0;
		sidePwr=0;
		upArrowDown=false;
		rightArrowDown=false;
		leftArrowDown=false;
		updateAll();
		draw();
	}
}

function gameLoop(){
	//update power
	if(map.alive){
		if(upArrowDown && mainPwr<10) mainPwr++;
		else if (!upArrowDown && mainPwr>0) mainPwr--;
		if(rightArrowDown && sidePwr<10) sidePwr++;
		if(leftArrowDown && sidePwr>-10) sidePwr--;
		if(!(rightArrowDown || leftArrowDown) && sidePwr>0) sidePwr--;
		else if(!(rightArrowDown || leftArrowDown) && sidePwr<0) sidePwr++;
		//move ship
		map.ship.pwr=mainPwr/10;
		map.ship.sidePwr=sidePwr/10;
		map.move();
		updateAll();
	}
	if(map.score>best){
		best=map.score;
		if(navigator.cookieEnabled){
			document.cookie="best="+best+"; expires=Thu, 18 Dec 2023 12:00:00 UTC";
		}
	}
	draw();
}<commit_msg>upated ui.js<commit_after>console.log("ui.js loaded");

var c;
var g;
var wid,hei;
var map;
var best;

var upArrowDown;
var rightArrowDown;
var leftArrowDown;
var mainPwr,sidePwr;

function init(){
	console.log("initialising");
	if(!navigator.cookieEnabled || document.cookie.search("best=")==-1){
		best=0;
	}
	else{
		var str=document.cookie.toString();
		best=Number(str.substring(5));
	}

	wid=500;
	hei=500;
	map=new Map(wid,hei);
	mainPwr=0;
	sidePwr=0;
	upArrowDown=false;
	rightArrowDown=false;
	leftArrowDown=false;
	c= document.getElementById("canvas0");
	var body=document.getElementById("body");
	body.addEventListener("keyup",keyUp);
	body.addEventListener("keydown",keyDown);
	g=c.getContext("2d");
	updateAll();
	draw();
	//setInterval("rotater()",25);
	setInterval("gameLoop()",100);
}

function draw(){
	//draw background
	g.fillStyle = "#FFFFFF";
	g.fillRect(0,0,wid,hei);
	if(map.alive){
		//draw ship
		g.fillStyle = "#FF0000";
		g.beginPath();
		g.moveTo(map.ship.vertices[0].x,map.ship.vertices[0].y);
		for(var i=1;i<5;i++) g.lineTo(map.ship.vertices[i].x,map.ship.vertices[i].y);
		g.closePath();
		g.fill();
		//draw flames
		//main
		g.fillStyle = "#ff6400";
		g.beginPath();
		g.moveTo(map.ship.mainFlame[0].x,map.ship.mainFlame[0].y);
		for(var i=1;i<3;i++) g.lineTo(map.ship.mainFlame[i].x,map.ship.mainFlame[i].y);
		g.closePath();
		g.fill();
		//side
		g.beginPath();
		g.moveTo(map.ship.sideFlame[0].x,map.ship.sideFlame[0].y);
		for(var i=1;i<3;i++) g.lineTo(map.ship.sideFlame[i].x,map.ship.sideFlame[i].y);
		g.closePath();
		g.fill();
		//draw asteroids
		g.fillStyle="#642010"
		for(var i=0;i<map.asteroids.length;i++){
			var s=map.asteroids[i].shape;
			g.beginPath();
			g.arc(s.center.x,s.center.y,s.radius,0,2*Math.PI);
			g.fill();
		}
		//draw score
		g.fillStyle = "#000000";
		g.font="bold 16px Courier New";
		g.textBaseline="top";
		g.textAlign="left";
		g.fillText("score: "+map.score,5,0);
		g.fillText("best : "+best,5,20);
		//draw power meters
		g.fillStyle="#999999";
		g.fillRect(410,470,80,20);
		g.fillRect(440,380,20,80);
		g.strokeStyle= "#000000";
		g.lineWidth=(3);
		g.strokeRect(410,470,80,20);
		g.strokeRect(440,380,20,80);
		g.beginPath();
		g.moveTo(450,470);
		g.lineTo(450,490);
		g.stroke();
		//fill in power meters
		g.fillStyle="#FF0000";
		g.fillRect(440,380,20,mainPwr*8);
		if(sidePwr>=0)g.fillRect(450,470,sidePwr*4,20);
		else g.fillRect(450+sidePwr*4,470,sidePwr*-4,20);
	}
	else{
		//game over screen
		g.fillStyle = "#000000";
		g.font="bold 42px Courier New";
		g.textBaseline="center";
		g.textAlign="center";
		g.fillText("GAME OVER!",wid/2,hei/2);
		g.font="bold 20px Courier New";
		g.fillText("score: "+map.score,wid/2,hei/2+40);
		g.fillText("best : "+best,wid/2,hei/2+65);
		g.fillText("Hit any key to start again!",wid/2,hei-40);
	}
}

function updateMainFlame(){
	with(obrengine){
		var forward=scaleVector(getUnitVector(map.ship.angle),map.ship.len/2);
		var side=scaleVector(getUnitVector(map.ship.angle+Math.PI/2),map.ship.wid/2);
		map.ship.mainFlame=[
			subtractVectors(map.ship.pos,addVectors(forward,side)),
			addVectors(map.ship.pos,subtractVectors(side,forward)),
			subtractVectors(map.ship.pos,scaleVector(forward,1+map.ship.pwr*2)),
		];
	}
}

function updateSideFlame(){
	with(obrengine){
		var forward=scaleVector(getUnitVector(map.ship.angle),map.ship.len/2);
		var side=scaleVector(getUnitVector(map.ship.angle+Math.PI/2),map.ship.wid/2);
		if(sidePwr>=0){
			map.ship.sideFlame=[
			addVectors(map.ship.pos,subtractVectors(forward,side)),
			addVectors(map.ship.pos,subtractVectors(scaleVector(forward,0.8),scaleVector(side,1+map.ship.sidePwr))),
			addVectors(map.ship.pos,subtractVectors(scaleVector(forward,0.6),side)),
			];
		}
		else{
			map.ship.sideFlame=[
			addVectors(map.ship.pos,addVectors(forward,side)),
			addVectors(map.ship.pos,addVectors(scaleVector(forward,0.8),scaleVector(side,1-map.ship.sidePwr))),
			addVectors(map.ship.pos,addVectors(scaleVector(forward,0.6),side)),
			];
		}
	}
}

function updateAll(){
	map.ship.updateVertices();
	updateMainFlame();
	updateSideFlame();
}

function keyDown(e){
	////console.log("key down. code="+e.keyCode);
	//left arrow: -ve side thrust
	if(e.keyCode==37){
		leftArrowDown=true;
		if(sidePwr>0) sidePwr=0;
	}
	//up arrow
	else if(e.keyCode==38){
		upArrowDown=true;
	}
	//right arrow: +ve side thrust
	else if(e.keyCode==39){
		rightArrowDown=true;
		if(sidePwr<0) sidePwr=0;
	}
	//down arrow
	else if(e.keyCode==40){
		mainPwr=0;
	}

	if(!map.alive){
		map=new Map(wid,hei);
		mainPwr=0;
		sidePwr=0;
		upArrowDown=false;
		rightArrowDown=false;
		leftArrowDown=false;
		updateAll();
		draw();
	}
}

function keyUp(e){
	////console.log("key up. code="+e.keyCode);
	//left arrow: -ve side thrust
	if(e.keyCode==37){
		leftArrowDown=false;
	}
	//up arrow
	else if(e.keyCode==38){
		upArrowDown=false;
	}
	//right arrow: +ve side thrust
	else if(e.keyCode==39){
		rightArrowDown=false;
	}
	//down arrow
	else if(e.keyCode==40){

	}
}

function gameLoop(){
	//update power
	if(map.alive){
		if(upArrowDown && mainPwr<10) mainPwr++;
		else if (!upArrowDown && mainPwr>0) mainPwr--;
		if(rightArrowDown && sidePwr<10) sidePwr++;
		if(leftArrowDown && sidePwr>-10) sidePwr--;
		if(!(rightArrowDown || leftArrowDown) && sidePwr>0) sidePwr--;
		else if(!(rightArrowDown || leftArrowDown) && sidePwr<0) sidePwr++;
		//move ship
		map.ship.pwr=mainPwr/10;
		map.ship.sidePwr=sidePwr/10;
		map.move();
		updateAll();
	}
	if(map.score>best){
		best=map.score;
		if(navigator.cookieEnabled){
			document.cookie="best="+best+"; expires=Thu, 18 Dec 2023 12:00:00 UTC";
		}
	}
	draw();
}<|endoftext|>


<commit_before>if (global.jasmine) return;

var jasmine = require('../../lib/jasmine-1.0.1');
var sys = require('util');

for(var key in jasmine) {
  global[key] = jasmine[key];
}

//Patch Jasmine for proper stack traces
jasmine.Spec.prototype.fail = function(e) {
  var expectationResult = new jasmine.ExpectationResult({
    passed: false,
    message: e ? jasmine.util.formatException(e) : 'Exception'
  });
  // PATCH
  if (e) {
   expectationResult.trace = e;
  }
  this.results_.addResult(expectationResult);
};

var isVerbose = false;
var showColors = true;
process.argv.forEach(function(arg){
  switch(arg) {
  case '--color': showColors = true; break;
  case '--noColor': showColors = false; break;
  case '--verbose': isVerbose = true; break;
  }
});

jasmine.executeSpecsInFolder(__dirname, function(runner, log){
  process.exit(runner.results().failedCount);
}, isVerbose, showColors);
<commit_msg>chore(specs.js): remove unused dependency<commit_after>if (global.jasmine) return;

var jasmine = require('../../lib/jasmine-1.0.1');

for(var key in jasmine) {
  global[key] = jasmine[key];
}

//Patch Jasmine for proper stack traces
jasmine.Spec.prototype.fail = function(e) {
  var expectationResult = new jasmine.ExpectationResult({
    passed: false,
    message: e ? jasmine.util.formatException(e) : 'Exception'
  });
  // PATCH
  if (e) {
   expectationResult.trace = e;
  }
  this.results_.addResult(expectationResult);
};

var isVerbose = false;
var showColors = true;
process.argv.forEach(function(arg){
  switch(arg) {
  case '--color': showColors = true; break;
  case '--noColor': showColors = false; break;
  case '--verbose': isVerbose = true; break;
  }
});

jasmine.executeSpecsInFolder(__dirname, function(runner, log){
  process.exit(runner.results().failedCount);
}, isVerbose, showColors);
<|endoftext|>


<commit_before>'use strict';

(function (angular, buildfire) {
  angular.module('eventsFeedPluginWidget', ['ngRoute', 'ngTouch', 'infinite-scroll', 'ui.bootstrap'])
    .config(['$routeProvider', function ($routeProvider) {
      $routeProvider
        .when('/feed', {
          templateUrl: 'templates/home.html',
          controllerAs: 'WidgetFeed',
          controller: 'WidgetFeedCtrl'
        })
        .when('/event/:eventIndex', {
          templateUrl: 'templates/eventDetails.html',
          controller: 'WidgetEventCtrl',
          controllerAs: 'WidgetEvent'
        })
        .otherwise('/feed');
    }])
    .filter('getDateFromTimestamp', function () {
      return function (input) {
        return new Date(input).getDate();
      };
    })
    .filter('getMonthFromTimestamp', function () {
      var monthsObj = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
      return function (input) {
        return monthsObj[new Date(input).getMonth()];
      };
    })
    .filter('getTimeZone', function () {

      return function (input) {
        input = new Date(input);
        var result = input.toString().match(/\((.+)\)/i);
        if (result.length)
          return result[1];
        else return "";
      };
    });
})(window.angular, window.buildfire);
<commit_msg>Added back button navigation on widget section<commit_after>'use strict';

(function (angular, buildfire) {
  angular.module('eventsFeedPluginWidget', ['ngRoute', 'ngTouch', 'infinite-scroll', 'ui.bootstrap'])
    .config(['$routeProvider', function ($routeProvider) {
      $routeProvider
        .when('/feed', {
          templateUrl: 'templates/home.html',
          controllerAs: 'WidgetFeed',
          controller: 'WidgetFeedCtrl'
        })
        .when('/event/:eventIndex', {
          templateUrl: 'templates/eventDetails.html',
          controller: 'WidgetEventCtrl',
          controllerAs: 'WidgetEvent'
        })
        .otherwise('/feed');
    }])
    .filter('getDateFromTimestamp', function () {
      return function (input) {
        return new Date(input).getDate();
      };
    })
    .filter('getMonthFromTimestamp', function () {
      var monthsObj = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
      return function (input) {
        return monthsObj[new Date(input).getMonth()];
      };
    })
    .filter('getTimeZone', function () {

      return function (input) {
        input = new Date(input);
        var result = input.toString().match(/\((.+)\)/i);
        if (result.length)
          return result[1];
        else return "";
      };
    })
      .run(['Location', '$location', function (Location, $location) {
        buildfire.navigation.onBackButtonClick = function(){
           if($location.path()!= "/feed"){
              Location.goTo('#/feed');
          };
        };
      }]);
})(window.angular, window.buildfire);
<|endoftext|>


<commit_before>import { options } from 'preact';

/** @type {number} */
let currentIndex;

/** @type {import('./internal').Component} */
let currentComponent;

/** @type {Array<import('./internal').Component>} */
let afterPaintEffects = [];

let oldBeforeRender = options._render;
let oldAfterDiff = options.diffed;
let oldCommit = options._commit;
let oldBeforeUnmount = options.unmount;

const RAF_TIMEOUT = 100;
let prevRaf;

options._render = vnode => {
	if (oldBeforeRender) oldBeforeRender(vnode);

	currentComponent = vnode._component;
	currentIndex = 0;

	if (currentComponent.__hooks) {
		currentComponent.__hooks._pendingEffects.forEach(invokeCleanup);
		currentComponent.__hooks._pendingEffects.forEach(invokeEffect);
		currentComponent.__hooks._pendingEffects = [];
	}
};

options.diffed = vnode => {
	if (oldAfterDiff) oldAfterDiff(vnode);

	const c = vnode._component;
	if (!c) return;

	const hooks = c.__hooks;
	if (hooks) {
		if (hooks._pendingEffects.length) {
			afterPaint(afterPaintEffects.push(c));
		}
	}
};

options._commit = (vnode, commitQueue) => {
	commitQueue.some(component => {
		try {
			component._renderCallbacks.forEach(invokeCleanup);
			component._renderCallbacks = component._renderCallbacks.filter(cb =>
				cb._value ? invokeEffect(cb) : true
			);
		} catch (e) {
			commitQueue.some(c => {
				if (c._renderCallbacks) c._renderCallbacks = [];
			});
			commitQueue = [];
			options._catchError(e, component._vnode);
		}
	});

	if (oldCommit) oldCommit(vnode, commitQueue);
};

options.unmount = vnode => {
	if (oldBeforeUnmount) oldBeforeUnmount(vnode);

	const c = vnode._component;
	if (!c) return;

	const hooks = c.__hooks;
	if (hooks) {
		try {
			hooks._list.forEach(hook => hook._cleanup && hook._cleanup());
		} catch (e) {
			options._catchError(e, c._vnode);
		}
	}
};

/**
 * Get a hook's state from the currentComponent
 * @param {number} index The index of the hook to get
 * @returns {import('./internal').HookState}
 */
function getHookState(index) {
	if (options._hook) options._hook(currentComponent);
	// Largely inspired by:
	// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs
	// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs
	// Other implementations to look at:
	// * https://codesandbox.io/s/mnox05qp8
	const hooks =
		currentComponent.__hooks ||
		(currentComponent.__hooks = { _list: [], _pendingEffects: [] });

	if (index >= hooks._list.length) {
		hooks._list.push({});
	}
	return hooks._list[index];
}

/**
 * @param {import('./index').StateUpdater<any>} initialState
 */
export function useState(initialState) {
	return useReducer(invokeOrReturn, initialState);
}

/**
 * @param {import('./index').Reducer<any, any>} reducer
 * @param {import('./index').StateUpdater<any>} initialState
 * @param {(initialState: any) => void} [init]
 * @returns {[ any, (state: any) => void ]}
 */
export function useReducer(reducer, initialState, init) {
	/** @type {import('./internal').ReducerHookState} */
	const hookState = getHookState(currentIndex++);
	if (!hookState._component) {
		hookState._component = currentComponent;

		hookState._value = [
			!init ? invokeOrReturn(undefined, initialState) : init(initialState),

			action => {
				const nextValue = reducer(hookState._value[0], action);
				if (hookState._value[0] !== nextValue) {
					hookState._value[0] = nextValue;
					hookState._component.setState({});
				}
			}
		];
	}

	return hookState._value;
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useEffect(callback, args) {
	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;

		currentComponent.__hooks._pendingEffects.push(state);
	}
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useLayoutEffect(callback, args) {
	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;

		currentComponent._renderCallbacks.push(state);
	}
}

export function useRef(initialValue) {
	return useMemo(() => ({ current: initialValue }), []);
}

/**
 * @param {object} ref
 * @param {() => object} createHandle
 * @param {any[]} args
 */
export function useImperativeHandle(ref, createHandle, args) {
	useLayoutEffect(
		() => {
			if (typeof ref == 'function') ref(createHandle());
			else if (ref) ref.current = createHandle();
		},
		args == null ? args : args.concat(ref)
	);
}

/**
 * @param {() => any} factory
 * @param {any[]} args
 */
export function useMemo(factory, args) {
	/** @type {import('./internal').MemoHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._args = args;
		state._factory = factory;
		return (state._value = factory());
	}

	return state._value;
}

/**
 * @param {() => void} callback
 * @param {any[]} args
 */
export function useCallback(callback, args) {
	return useMemo(() => callback, args);
}

/**
 * @param {import('./internal').PreactContext} context
 */
export function useContext(context) {
	const provider = currentComponent.context[context._id];
	if (!provider) return context._defaultValue;
	const state = getHookState(currentIndex++);
	// This is probably not safe to convert to "!"
	if (state._value == null) {
		state._value = true;
		provider.sub(currentComponent);
	}
	return provider.props.value;
}

/**
 * Display a custom label for a custom hook for the devtools panel
 * @type {<T>(value: T, cb?: (value: T) => string | number) => void}
 */
export function useDebugValue(value, formatter) {
	if (options.useDebugValue) {
		options.useDebugValue(formatter ? formatter(value) : value);
	}
}

export function useErrorBoundary(cb) {
	const state = getHookState(currentIndex++);
	const errState = useState();
	state._value = cb;
	if (!currentComponent.componentDidCatch) {
		currentComponent.componentDidCatch = err => {
			if (state._value) state._value(err);
			errState[1](err);
		};
	}
	return [
		errState[0],
		() => {
			errState[1](undefined);
		}
	];
}

/**
 * After paint effects consumer.
 */
function flushAfterPaintEffects() {
	afterPaintEffects.some(component => {
		if (component._parentDom) {
			const effects = component.__hooks._pendingEffects;
			component.__hooks._pendingEffects = [];
			try {
				effects.forEach(invokeCleanup);
				effects.forEach(invokeEffect);
			} catch (e) {
				options._catchError(e, component._vnode);
				return true;
			}
		}
	});
	afterPaintEffects = [];
}

/**
 * Schedule a callback to be invoked after the browser has a chance to paint a new frame.
 * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after
 * the next browser frame.
 *
 * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked
 * even if RAF doesn't fire (for example if the browser tab is not visible)
 *
 * @param {() => void} callback
 */
function afterNextFrame(callback) {
	const done = () => {
		clearTimeout(timeout);
		cancelAnimationFrame(raf);
		setTimeout(callback);
	};
	const timeout = setTimeout(done, RAF_TIMEOUT);

	let raf;
	if (typeof window != 'undefined') {
		raf = requestAnimationFrame(done);
	}
}

// Note: if someone used options.debounceRendering = requestAnimationFrame,
// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.
// Perhaps this is not such a big deal.
/**
 * Schedule afterPaintEffects flush after the browser paints
 * @param {number} newQueueLength
 */
function afterPaint(newQueueLength) {
	if (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {
		prevRaf = options.requestAnimationFrame;
		(prevRaf || afterNextFrame)(flushAfterPaintEffects);
	}
}

/**
 * @param {import('./internal').EffectHookState} hook
 */
function invokeCleanup(hook) {
	if (hook._cleanup) hook._cleanup();
}

/**
 * Invoke a Hook's effect
 * @param {import('./internal').EffectHookState} hook
 */
function invokeEffect(hook) {
	const result = hook._value();
	if (typeof result == 'function') hook._cleanup = result;
}

/**
 * @param {any[]} oldArgs
 * @param {any[]} newArgs
 */
function argsChanged(oldArgs, newArgs) {
	return !oldArgs || newArgs.some((arg, index) => arg !== oldArgs[index]);
}

function invokeOrReturn(arg, f) {
	return typeof f == 'function' ? f(arg) : f;
}
<commit_msg>Refactor `_pendingEffects` queue reset<commit_after>import { options } from 'preact';

/** @type {number} */
let currentIndex;

/** @type {import('./internal').Component} */
let currentComponent;

/** @type {Array<import('./internal').Component>} */
let afterPaintEffects = [];

let oldBeforeRender = options._render;
let oldAfterDiff = options.diffed;
let oldCommit = options._commit;
let oldBeforeUnmount = options.unmount;

const RAF_TIMEOUT = 100;
let prevRaf;

options._render = vnode => {
	if (oldBeforeRender) oldBeforeRender(vnode);

	currentComponent = vnode._component;
	currentIndex = 0;

	if (currentComponent.__hooks) {
		currentComponent.__hooks._pendingEffects.forEach(invokeCleanup);
		currentComponent.__hooks._pendingEffects.forEach(invokeEffect);
		currentComponent.__hooks._pendingEffects = [];
	}
};

options.diffed = vnode => {
	if (oldAfterDiff) oldAfterDiff(vnode);

	const c = vnode._component;
	if (!c) return;

	const hooks = c.__hooks;
	if (hooks) {
		if (hooks._pendingEffects.length) {
			afterPaint(afterPaintEffects.push(c));
		}
	}
};

options._commit = (vnode, commitQueue) => {
	commitQueue.some(component => {
		try {
			component._renderCallbacks.forEach(invokeCleanup);
			component._renderCallbacks = component._renderCallbacks.filter(cb =>
				cb._value ? invokeEffect(cb) : true
			);
		} catch (e) {
			commitQueue.some(c => {
				if (c._renderCallbacks) c._renderCallbacks = [];
			});
			commitQueue = [];
			options._catchError(e, component._vnode);
		}
	});

	if (oldCommit) oldCommit(vnode, commitQueue);
};

options.unmount = vnode => {
	if (oldBeforeUnmount) oldBeforeUnmount(vnode);

	const c = vnode._component;
	if (!c) return;

	const hooks = c.__hooks;
	if (hooks) {
		try {
			hooks._list.forEach(hook => hook._cleanup && hook._cleanup());
		} catch (e) {
			options._catchError(e, c._vnode);
		}
	}
};

/**
 * Get a hook's state from the currentComponent
 * @param {number} index The index of the hook to get
 * @returns {import('./internal').HookState}
 */
function getHookState(index) {
	if (options._hook) options._hook(currentComponent);
	// Largely inspired by:
	// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs
	// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs
	// Other implementations to look at:
	// * https://codesandbox.io/s/mnox05qp8
	const hooks =
		currentComponent.__hooks ||
		(currentComponent.__hooks = { _list: [], _pendingEffects: [] });

	if (index >= hooks._list.length) {
		hooks._list.push({});
	}
	return hooks._list[index];
}

/**
 * @param {import('./index').StateUpdater<any>} initialState
 */
export function useState(initialState) {
	return useReducer(invokeOrReturn, initialState);
}

/**
 * @param {import('./index').Reducer<any, any>} reducer
 * @param {import('./index').StateUpdater<any>} initialState
 * @param {(initialState: any) => void} [init]
 * @returns {[ any, (state: any) => void ]}
 */
export function useReducer(reducer, initialState, init) {
	/** @type {import('./internal').ReducerHookState} */
	const hookState = getHookState(currentIndex++);
	if (!hookState._component) {
		hookState._component = currentComponent;

		hookState._value = [
			!init ? invokeOrReturn(undefined, initialState) : init(initialState),

			action => {
				const nextValue = reducer(hookState._value[0], action);
				if (hookState._value[0] !== nextValue) {
					hookState._value[0] = nextValue;
					hookState._component.setState({});
				}
			}
		];
	}

	return hookState._value;
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useEffect(callback, args) {
	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;

		currentComponent.__hooks._pendingEffects.push(state);
	}
}

/**
 * @param {import('./internal').Effect} callback
 * @param {any[]} args
 */
export function useLayoutEffect(callback, args) {
	/** @type {import('./internal').EffectHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._value = callback;
		state._args = args;

		currentComponent._renderCallbacks.push(state);
	}
}

export function useRef(initialValue) {
	return useMemo(() => ({ current: initialValue }), []);
}

/**
 * @param {object} ref
 * @param {() => object} createHandle
 * @param {any[]} args
 */
export function useImperativeHandle(ref, createHandle, args) {
	useLayoutEffect(
		() => {
			if (typeof ref == 'function') ref(createHandle());
			else if (ref) ref.current = createHandle();
		},
		args == null ? args : args.concat(ref)
	);
}

/**
 * @param {() => any} factory
 * @param {any[]} args
 */
export function useMemo(factory, args) {
	/** @type {import('./internal').MemoHookState} */
	const state = getHookState(currentIndex++);
	if (argsChanged(state._args, args)) {
		state._args = args;
		state._factory = factory;
		return (state._value = factory());
	}

	return state._value;
}

/**
 * @param {() => void} callback
 * @param {any[]} args
 */
export function useCallback(callback, args) {
	return useMemo(() => callback, args);
}

/**
 * @param {import('./internal').PreactContext} context
 */
export function useContext(context) {
	const provider = currentComponent.context[context._id];
	if (!provider) return context._defaultValue;
	const state = getHookState(currentIndex++);
	// This is probably not safe to convert to "!"
	if (state._value == null) {
		state._value = true;
		provider.sub(currentComponent);
	}
	return provider.props.value;
}

/**
 * Display a custom label for a custom hook for the devtools panel
 * @type {<T>(value: T, cb?: (value: T) => string | number) => void}
 */
export function useDebugValue(value, formatter) {
	if (options.useDebugValue) {
		options.useDebugValue(formatter ? formatter(value) : value);
	}
}

export function useErrorBoundary(cb) {
	const state = getHookState(currentIndex++);
	const errState = useState();
	state._value = cb;
	if (!currentComponent.componentDidCatch) {
		currentComponent.componentDidCatch = err => {
			if (state._value) state._value(err);
			errState[1](err);
		};
	}
	return [
		errState[0],
		() => {
			errState[1](undefined);
		}
	];
}

/**
 * After paint effects consumer.
 */
function flushAfterPaintEffects() {
	afterPaintEffects.some(component => {
		if (component._parentDom) {
			try {
				component.__hooks._pendingEffects.forEach(invokeCleanup);
				component.__hooks._pendingEffects.forEach(invokeEffect);
				component.__hooks._pendingEffects = [];
			} catch (e) {
				component.__hooks._pendingEffects = [];
				options._catchError(e, component._vnode);
				return true;
			}
		}
	});
	afterPaintEffects = [];
}

/**
 * Schedule a callback to be invoked after the browser has a chance to paint a new frame.
 * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after
 * the next browser frame.
 *
 * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked
 * even if RAF doesn't fire (for example if the browser tab is not visible)
 *
 * @param {() => void} callback
 */
function afterNextFrame(callback) {
	const done = () => {
		clearTimeout(timeout);
		cancelAnimationFrame(raf);
		setTimeout(callback);
	};
	const timeout = setTimeout(done, RAF_TIMEOUT);

	let raf;
	if (typeof window != 'undefined') {
		raf = requestAnimationFrame(done);
	}
}

// Note: if someone used options.debounceRendering = requestAnimationFrame,
// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.
// Perhaps this is not such a big deal.
/**
 * Schedule afterPaintEffects flush after the browser paints
 * @param {number} newQueueLength
 */
function afterPaint(newQueueLength) {
	if (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {
		prevRaf = options.requestAnimationFrame;
		(prevRaf || afterNextFrame)(flushAfterPaintEffects);
	}
}

/**
 * @param {import('./internal').EffectHookState} hook
 */
function invokeCleanup(hook) {
	if (hook._cleanup) hook._cleanup();
}

/**
 * Invoke a Hook's effect
 * @param {import('./internal').EffectHookState} hook
 */
function invokeEffect(hook) {
	const result = hook._value();
	if (typeof result == 'function') hook._cleanup = result;
}

/**
 * @param {any[]} oldArgs
 * @param {any[]} newArgs
 */
function argsChanged(oldArgs, newArgs) {
	return !oldArgs || newArgs.some((arg, index) => arg !== oldArgs[index]);
}

function invokeOrReturn(arg, f) {
	return typeof f == 'function' ? f(arg) : f;
}
<|endoftext|>


<commit_before>/*
MIT License

Copyright (c) 2016 José Rafael Vieira

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

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

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

'use strict';

module.exports = chain;
//every setting defaults to false
var settings = Object.preventExtensions({
	owncontext: false, //functions remain in owner's context
	uniqueness: false, //prevent duplicate objects in chain
	allowloops: false, //allow loops (only happens when chaining Chainchainchain objects)
	setchained: false //values are set on its youngest owner in chain
});

const chi = Symbol('chi');

var handler = {
	get: function (arr, prop) {
		if (prop === chi) return arr;
		//if (prop === rvk) return arr.
		//get youngest
		var p;
		for (let o of arr) {
			if (typeof o[prop] !== 'undefined') {
				//x && y => if x is true returns y, else returns x
				p = o[prop] instanceof Function ? o[prop].bind(!settings.owncontext && arr[0] || o) : o[prop];
			}
		}
		return p;
	},
	set: function (arr, prop, value) {
		var origin = arr[0];
		if (!settings.setchained) return origin[prop] = value;
		//set youngest
		for (let o of arr) {
			if (typeof o[prop] !== 'undefined') {
				return o[prop] = value;
			}
		}
		console.warn(prop+' is not a chained property');
		return false;
	}
}

function chain (o) {
	//validate o
	if (typeof o === 'undefined') throw new TypeError('Argument undefined');
	//validate ch
	console.log('// ch init');
	//FINDLOOPS

	return new Proxy([...arguments], handler);
}

Object.defineProperties(chain, {

	set:{
		value: new Proxy(settings, {
			get: function (target, prop) {
				return !!target[prop];
			},
			set: function (target, prop, value) {
				//if (!(prop in target)) throw new Error(prop+' is not a setting');
				if (typeof value !== 'boolean') console.warn('Chain settings should be Boolean, assuming '+!!value+' for '+prop);
				return target[prop] = !!value;
			}
		})
	},
	//returns origin object
	origin: {
		value: function (ch) {
			return ch[chi][0] || false;
		}
	},
	//returns chain's array of objects
	is: {
		value: function (ch) { //leaks
			return ch[chi] ? true : false;
		}
	},
	//returns chain's array of objects
	arr: {
		value: function (ch) { //leaks
			return ch[chi] ? [...ch[chi]] : false;
		}
	},
	//MANIPULATION
	//adds objects to end of chain
	add: {
		value: function (ch, oo = []) {
			if (!ch[chi]) throw new TypeError(ch+' is not a chain');
			if (!(oo instanceof Array)) oo = [oo];
			//appends objects to chain
			ch[chi].push(...oo);
			//FINDLOOPS

			return [...ch[chi]];
		}
	},
	//adds objects to beggining of chain
	pre: {
		value: function (ch, oo = []) {
			if (!ch[chi]) throw new TypeError(ch+' is not a chain');
			if (!(oo instanceof Array)) oo = [oo];
			//prepends objects to chain
			ch[chi].splice(1, 0, oo);
			//FINDLOOPS

			return [...ch[chi]];
		}
	},
	//removes objects from chain
	rem: {
		value: function (ch, oo = []) {
			if (!ch[chi]) throw new TypeError(ch+' is not a chain');
			if (!(oo instanceof Array)) oo = [oo];
			//filters objects out of chain
			for (let i = 0; i < oo.length; i ++) {
				ch[chi] = ch[chi].filter(function (o) {
				    return o !== oo[i];
				});
			}

			return [...ch[chi]];
		}
	},
	//replaces objects from chain
	rep: {
		value: function (ch, x, n) {
			if (!ch[chi]) throw new TypeError(ch+' is not a chain');
			//replaces objects in chain
			while (!(ch[chi].indexOf(x) < 0)) {
				ch[chi].splice(ch[chi].indexOf(x),1,n);
			}
			//FINDLOOPS

			return [...ch[chi]];
		}
	},
	//returns array of properties in chain
	raw: {
		value: function (ch, prop, callback) {
			if (!ch[chi]) throw new TypeError(ch+' is not a chain');
			//validate p
			if (typeof prop === 'undefined') throw new TypeError('Argument undefined');

			var raw = [];
			var own = [];

			for (let o of ch[chi]) {
				//x && y => if x is true returns y, else returns x
				raw.push(o[prop] instanceof Function ? o[prop].bind(!settings.owncontext && ch[chi][0] || o) : o[prop]);
				if (callback) own.push(o);
			}

			return callback ? callback(raw, own) : raw;
		}
	},

	//if you create a loop there is a RangeError: Maximum call stack size exceeded
	//so this method and the allowloops setting is obsolete ?
	findloop: {
		value: function (ch) {
			if (ch[chi]) {
				var arr = [ch[chi]];
				for (let i = 0; i < ch[chi].length; i++) {
					let oo = ch[chi][i];
					if(arr.indexOf(oo) > -1) {
						console.warn('Looping', oo);
						if (!settings.allowloops) throw new Error('loop in chain tree');
						return oo;
					} else {
						chain.findloop(oo);
						arr.push(oo);
						console.info('Findlooping... '+oo.name);
					}
				}
			}
			return false;
		}
	}

});
<commit_msg>Updated findloop<commit_after>/*
MIT License

Copyright (c) 2016 José Rafael Vieira

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

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

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

'use strict';

//export default chain; //import chain from 'chainchainchain'
module.exports = chain;

//every setting defaults to false
var settings = Object.preventExtensions({
	owncontext: false, //functions remain in owner's context
	uniqueness: false, //prevent duplicate objects in chain
	allowloops: false, //allow loops (only happens when chaining Chainchainchain objects)
	setchained: false //values are set on its youngest owner in chain
});

const chi = Symbol('chi');

var handler = {
	get: function (arr, prop) {
		if (prop === chi) return arr;
		//if (prop === rvk) return arr.
		//get youngest
		var p;
		for (let o of arr) {
			if (typeof o[prop] !== 'undefined') {
				//x && y => if x is true returns y, else returns x
				p = o[prop] instanceof Function ? o[prop].bind(!settings.owncontext && arr[0] || o) : o[prop];
			}
		}
		return p;
	},
	set: function (arr, prop, value) {
		var origin = arr[0];
		if (!settings.setchained) return origin[prop] = value;
		//set youngest
		for (let o of arr) {
			if (typeof o[prop] !== 'undefined') {
				return o[prop] = value;
			}
		}
		console.warn(prop+' is not a chained property');
		return false;
	}
}

function chain (...arr) {
	//validate o
	if (typeof arr === 'undefined') throw new TypeError('Argument undefined');
	//validate ch
	console.log('// ch init');
	//FINDLOOPS

	return new Proxy(arr, handler);
}

Object.defineProperties(chain, {

	set:{
		value: new Proxy(settings, {
			get: function (target, prop) {
				return !!target[prop];
			},
			set: function (target, prop, value) {
				//if (!(prop in target)) throw new Error(prop+' is not a setting');
				if (typeof value !== 'boolean') console.warn('Chain settings should be Boolean, assuming '+!!value+' for '+prop);
				return target[prop] = !!value;
			}
		})
	},
	//returns origin object
	origin: {
		value: function (ch) {
			return ch[chi][0] || false;
		}
	},
	//returns chain's array of objects
	is: {
		value: function (ch) { //leaks
			return ch[chi] ? true : false;
		}
	},
	//returns chain's array of objects
	arr: {
		value: function (ch) { //leaks
			return ch[chi] ? [...ch[chi]] : false;
		}
	},
	//MANIPULATION
	//adds objects to end of chain
	add: {
		value: function (ch, oo = []) {
			if (!ch[chi]) throw new TypeError(ch+' is not a chain');
			if (!(oo instanceof Array)) oo = [oo];
			//appends objects to chain
			ch[chi].push(...oo);
			//FINDLOOPS

			return [...ch[chi]];
		}
	},
	//adds objects to beggining of chain
	pre: {
		value: function (ch, oo = []) {
			if (!ch[chi]) throw new TypeError(ch+' is not a chain');
			if (!(oo instanceof Array)) oo = [oo];
			//prepends objects to chain
			ch[chi].splice(1, 0, oo);
			//FINDLOOPS

			return [...ch[chi]];
		}
	},
	//removes objects from chain
	rem: {
		value: function (ch, xx = []) {
			if (!ch[chi]) throw new TypeError(ch+' is not a chain');
			if (!(xx instanceof Array)) xx = [xx];
			//filters objects out of chain
			for (let x of xx) {
				ch[chi] = ch[chi].filter(function (o) {
				    return o !== x;
				});
			}

			return [...ch[chi]];
		}
	},
	//replaces objects from chain
	rep: {
		value: function (ch, x, o) {
			if (!ch[chi]) throw new TypeError(ch+' is not a chain');
			//replaces objects in chain
			while (!(ch[chi].indexOf(x) < 0)) {
				console.info(ch[chi], x ,ch[chi].indexOf(x));
				ch[chi].splice(ch[chi].indexOf(x),1,o);
				console.info(ch[chi]);
			}
			//FINDLOOPS

			return [...ch[chi]];
		}
	},
	//returns array of properties in chain
	raw: {
		value: function (ch, prop, callback) {
			if (!ch[chi]) throw new TypeError(ch+' is not a chain');
			//validate p
			if (typeof prop === 'undefined') throw new TypeError('Argument undefined');

			var raw = [];
			var own = [];

			for (let o of ch[chi]) {
				//x && y => if x is true returns y, else returns x
				raw.push(o[prop] instanceof Function ? o[prop].bind(!settings.owncontext && ch[chi][0] || o) : o[prop]);
				if (callback) own.push(o);
			}

			return callback ? callback(raw, own) : raw;
		}
	},

	//if you create a loop there is a RangeError: Maximum call stack size exceeded
	//so this method and the allowloops setting is obsolete ?
	findloop: {
		value: function (ch, set = new Set()) {
			set.add(ch);
			for (let o of ch[chi]) {
				if ( chain.is(o) && ( set.has(o) || chain.findloop(o, set) ) ) {
					return o;
				}
			}
			return false;
		}
	}

});
<|endoftext|>


<commit_before>"use strict";
/*jshint phantom: true*/
/*eslint-env phantomjs*/
var fs = require("fs"),
    loadTests = require("./node_loader.js");
require("./bdd.js"); /*global run*/
loadTests(function (path) {
    return fs.read(path);
});
run();
<commit_msg>Use common loader<commit_after>"use strict";
/*jshint phantom: true*/
/*eslint-env phantomjs*/

var fs = require("fs");
require("./loader.js"); /*global loadGpfAndTests*/

loadGpfAndTests({
    global: global,
    parameters: require("system").args.slice(1),
    // https://groups.google.com/forum/#!msg/phantomjs/OswbWiKrLYI/ndoXvK13OrIJ
    gpfPath: phantom.libraryPath.split("/").slice(0, -2).join(fs.separator),
    pathSeparator: fs.separator,
    log: function (text) {
        console.log(text);
    },
    exit: phantom.exit,
    require: require,
    read: function (filePath) {
        return fs.read(filePath);
    }
});
<|endoftext|>


<commit_before>function(doc) {
    if (doc) {
      emit(doc.uniqueId, {
	    "id" :                 doc._id,
        "aliasOf":             doc.aliasOf,
		"defaultValue":        doc.defaultValue,
		"definition":	       doc.definition,
		"localUniqueId":       doc.localUniqueId,
		"notes":	           doc.notes,
		"termLabel":           doc.termLabel,
 		"type":                doc.type,
		"uniqueId":	           doc.uniqueId,
		"uses":	               doc.uses,
		"valueSpace":          doc.valueSpace
      });
  }
};<commit_msg>Added _id and _rev fields to entries to facilitate updating records.<commit_after>function(doc) {
    if (doc) {
      emit(doc.uniqueId, {
	    "_id" :                doc._id,
	    "_rev" :               doc._rev,
	    "id" :                 doc._id,
        "aliasOf":             doc.aliasOf,
		"defaultValue":        doc.defaultValue,
		"definition":	       doc.definition,
		"localUniqueId":       doc.localUniqueId,
		"notes":	           doc.notes,
		"termLabel":           doc.termLabel,
 		"type":                doc.type,
		"uniqueId":	           doc.uniqueId,
		"uses":	               doc.uses,
		"valueSpace":          doc.valueSpace
      });
  }
};<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict'

const tests = require('interface-ipfs-core')
const isNode = require('detect-node')
const CommonFactory = require('./utils/interface-common-factory')
const ipfsClient = require('../src')
const isWindows = process.platform && process.platform === 'win32'

describe('interface-ipfs-core tests', () => {
  const defaultCommonFactory = CommonFactory.create()

  tests.bitswap(defaultCommonFactory, {
    skip: [
      // bitswap.stat
      {
        name: 'should not get bitswap stats when offline',
        reason: 'FIXME go-ipfs returns an error https://github.com/ipfs/go-ipfs/issues/4078'
      },
      // bitswap.wantlist
      {
        name: 'should not get the wantlist when offline',
        reason: 'FIXME go-ipfs returns an error https://github.com/ipfs/go-ipfs/issues/4078'
      },
      // bitswap.unwant
      {
        name: 'should remove a key from the wantlist',
        reason: 'FIXME why is this skipped?'
      },
      {
        name: 'should not remove a key from the wantlist when offline',
        reason: 'FIXME go-ipfs returns an error https://github.com/ipfs/go-ipfs/issues/4078'
      }
    ]
  })

  tests.block(defaultCommonFactory, {
    skip: [{
      name: 'should get a block added as CIDv1 with a CIDv0',
      reason: 'go-ipfs does not support the `version` param'
    }]
  })

  tests.bootstrap(defaultCommonFactory)

  tests.config(defaultCommonFactory, {
    skip: [
      // config.replace
      {
        name: 'replace',
        reason: 'FIXME Waiting for fix on go-ipfs https://github.com/ipfs/js-ipfs-http-client/pull/307#discussion_r69281789 and https://github.com/ipfs/go-ipfs/issues/2927'
      }
    ]
  })

  tests.dag(defaultCommonFactory, {
    skip: [
      // dag.tree
      {
        name: 'tree',
        reason: 'TODO vmx 2018-02-22: Currently the tree API is not exposed in go-ipfs'
      },
      // dag.get:
      {
        name: 'should get a dag-pb node local value',
        reason: 'FIXME vmx 2018-02-22: Currently not supported in go-ipfs, it might be possible once https://github.com/ipfs/go-ipfs/issues/4728 is done'
      },
      {
        name: 'should get dag-pb value via dag-cbor node',
        reason: 'FIXME vmx 2018-02-22: Currently not supported in go-ipfs, it might be possible once https://github.com/ipfs/go-ipfs/issues/4728 is done'
      },
      {
        name: 'should get by CID string + path',
        reason: 'FIXME vmx 2018-02-22: Currently not supported in go-ipfs, it might be possible once https://github.com/ipfs/go-ipfs/issues/4728 is done'
      },
      {
        name: 'should get only a CID, due to resolving locally only',
        reason: 'FIXME: go-ipfs does not support localResolve option'
      }
    ]
  })

  tests.dht(defaultCommonFactory, {
    skip: [
      // dht.findpeer
      {
        name: 'should fail to find other peer if peer does not exist',
        reason: 'FIXME checking what is exactly go-ipfs returning https://github.com/ipfs/go-ipfs/issues/3862#issuecomment-294168090'
      },
      // dht.findprovs
      {
        name: 'should provide from one node and find it through another node',
        reason: 'FIXME go-ipfs endpoint doesn\'t conform with the others https://github.com/ipfs/go-ipfs/issues/5047'
      },
      // dht.get
      {
        name: 'should get a value after it was put on another node',
        reason: 'FIXME go-ipfs errors with  Error: key was not found (type 6) https://github.com/ipfs/go-ipfs/issues/3862'
      }
    ]
  })

  tests.filesRegular(defaultCommonFactory, {
    skip: [
      // .add
      isNode ? null : {
        name: 'should add a nested directory as array of tupples',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      isNode ? null : {
        name: 'should add a nested directory as array of tupples with progress',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .addPullStream
      isNode ? null : {
        name: 'should add pull stream of valid files and dirs',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .addReadableStream
      isNode ? null : {
        name: 'should add readable stream of valid files and dirs',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .addFromStream
      isNode ? null : {
        name: 'addFromStream',
        reason: 'Not designed to run in the browser'
      },
      // .addFromFs
      isNode ? null : {
        name: 'addFromFs',
        reason: 'Not designed to run in the browser'
      },
      // .addFromURL
      isNode ? null : {
        name: 'addFromURL',
        reason: 'Not designed to run in the browser'
      },
      // TODO: remove when interface-ipfs-core updated
      isNode ? null : {
        name: 'addFromUrl',
        reason: 'Not designed to run in the browser'
      },
      // .catPullStream
      {
        name: 'should export a chunk of a file',
        reason: 'TODO not implemented in go-ipfs yet'
      },
      {
        name: 'should export a chunk of a file in a Pull Stream',
        reason: 'TODO not implemented in go-ipfs yet'
      },
      {
        name: 'should export a chunk of a file in a Readable Stream',
        reason: 'TODO not implemented in go-ipfs yet'
      },
      // .get
      isNode ? null : {
        name: 'should get a directory',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .ls
      isNode ? null : {
        name: 'should ls with a base58 encoded CID',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .lsPullStream
      isNode ? null : {
        name: 'should pull stream ls with a base58 encoded CID',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .lsReadableStream
      isNode ? null : {
        name: 'should readable stream ls with a base58 encoded CID',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .refs
      {
        name: 'dag refs test',
        reason: 'FIXME unskip when 0.4.21 is released'
      }
    ]
  })

  tests.filesMFS(defaultCommonFactory)

  tests.key(defaultCommonFactory, {
    skip: [
      // key.export
      {
        name: 'export',
        reason: 'TODO not implemented in go-ipfs yet'
      },
      // key.import
      {
        name: 'import',
        reason: 'TODO not implemented in go-ipfs yet'
      }
    ]
  })

  tests.miscellaneous(defaultCommonFactory, {
    skip: [
      // stop
      {
        name: 'should stop the node',
        reason: 'FIXME go-ipfs returns an error https://github.com/ipfs/go-ipfs/issues/4078'
      }
    ]
  })

  tests.name(CommonFactory.create({
    spawnOptions: {
      args: ['--offline']
    }
  }))

  // TODO: uncomment after https://github.com/ipfs/interface-ipfs-core/pull/361 being merged and a new release
  tests.namePubsub(CommonFactory.create({
    spawnOptions: {
      args: ['--enable-namesys-pubsub'],
      initOptions: { bits: 1024 }
    }
  }), {
    skip: [
      // name.pubsub.cancel
      {
        name: 'should cancel a subscription correctly returning true',
        reason: 'go-ipfs is really slow for publishing and resolving ipns records, unless in offline mode'
      },
      // name.pubsub.subs
      {
        name: 'should get the list of subscriptions updated after a resolve',
        reason: 'go-ipfs is really slow for publishing and resolving ipns records, unless in offline mode'
      }
    ]
  })

  tests.object(defaultCommonFactory)

  tests.pin(defaultCommonFactory)

  tests.ping(defaultCommonFactory, {
    skip: [
      {
        name: 'should fail when pinging an unknown peer over pull stream',
        reason: 'FIXME go-ipfs return success with text: Looking up peer <cid>'
      },
      {
        name: 'should fail when pinging peer that is not available over readable stream',
        reason: 'FIXME go-ipfs return success with text: Looking up peer <cid>'
      },
      {
        name: 'should fail when pinging a peer that is not available',
        reason: 'FIXME go-ipfs return success with text: Looking up peer <cid>'
      }
    ]
  })

  tests.pubsub(CommonFactory.create({
    spawnOptions: {
      args: ['--enable-pubsub-experiment'],
      initOptions: { bits: 1024 }
    }
  }), {
    skip: isNode ? [
      // pubsub.subscribe
      isWindows ? {
        name: 'should send/receive 100 messages',
        reason: 'FIXME https://github.com/ipfs/interface-ipfs-core/pull/188#issuecomment-354673246 and https://github.com/ipfs/go-ipfs/issues/4778'
      } : null,
      isWindows ? {
        name: 'should receive multiple messages',
        reason: 'FIXME https://github.com/ipfs/interface-ipfs-core/pull/188#issuecomment-354673246 and https://github.com/ipfs/go-ipfs/issues/4778'
      } : null
    ] : {
      reason: 'FIXME pubsub is not supported in the browser https://github.com/ipfs/js-ipfs-http-client/issues/518'
    }
  })

  tests.repo(defaultCommonFactory)

  tests.stats(defaultCommonFactory)

  tests.swarm(CommonFactory.create({
    createSetup ({ ipfsFactory, nodes }) {
      return callback => {
        callback(null, {
          spawnNode (repoPath, config, cb) {
            if (typeof repoPath === 'function') {
              cb = repoPath
              repoPath = undefined
            }

            if (typeof config === 'function') {
              cb = config
              config = undefined
            }

            const spawnOptions = { repoPath, config, initOptions: { bits: 1024 } }

            ipfsFactory.spawn(spawnOptions, (err, _ipfsd) => {
              if (err) {
                return cb(err)
              }

              nodes.push(_ipfsd)
              cb(null, ipfsClient(_ipfsd.apiAddr))
            })
          }
        })
      }
    }
  }))
})
<commit_msg>chore: use test profile for swarm tests (#1038)<commit_after>/* eslint-env mocha */
'use strict'

const tests = require('interface-ipfs-core')
const isNode = require('detect-node')
const CommonFactory = require('./utils/interface-common-factory')
const ipfsClient = require('../src')
const isWindows = process.platform && process.platform === 'win32'

describe('interface-ipfs-core tests', () => {
  const defaultCommonFactory = CommonFactory.create()

  tests.bitswap(defaultCommonFactory, {
    skip: [
      // bitswap.stat
      {
        name: 'should not get bitswap stats when offline',
        reason: 'FIXME go-ipfs returns an error https://github.com/ipfs/go-ipfs/issues/4078'
      },
      // bitswap.wantlist
      {
        name: 'should not get the wantlist when offline',
        reason: 'FIXME go-ipfs returns an error https://github.com/ipfs/go-ipfs/issues/4078'
      },
      // bitswap.unwant
      {
        name: 'should remove a key from the wantlist',
        reason: 'FIXME why is this skipped?'
      },
      {
        name: 'should not remove a key from the wantlist when offline',
        reason: 'FIXME go-ipfs returns an error https://github.com/ipfs/go-ipfs/issues/4078'
      }
    ]
  })

  tests.block(defaultCommonFactory, {
    skip: [{
      name: 'should get a block added as CIDv1 with a CIDv0',
      reason: 'go-ipfs does not support the `version` param'
    }]
  })

  tests.bootstrap(defaultCommonFactory)

  tests.config(defaultCommonFactory, {
    skip: [
      // config.replace
      {
        name: 'replace',
        reason: 'FIXME Waiting for fix on go-ipfs https://github.com/ipfs/js-ipfs-http-client/pull/307#discussion_r69281789 and https://github.com/ipfs/go-ipfs/issues/2927'
      }
    ]
  })

  tests.dag(defaultCommonFactory, {
    skip: [
      // dag.tree
      {
        name: 'tree',
        reason: 'TODO vmx 2018-02-22: Currently the tree API is not exposed in go-ipfs'
      },
      // dag.get:
      {
        name: 'should get a dag-pb node local value',
        reason: 'FIXME vmx 2018-02-22: Currently not supported in go-ipfs, it might be possible once https://github.com/ipfs/go-ipfs/issues/4728 is done'
      },
      {
        name: 'should get dag-pb value via dag-cbor node',
        reason: 'FIXME vmx 2018-02-22: Currently not supported in go-ipfs, it might be possible once https://github.com/ipfs/go-ipfs/issues/4728 is done'
      },
      {
        name: 'should get by CID string + path',
        reason: 'FIXME vmx 2018-02-22: Currently not supported in go-ipfs, it might be possible once https://github.com/ipfs/go-ipfs/issues/4728 is done'
      },
      {
        name: 'should get only a CID, due to resolving locally only',
        reason: 'FIXME: go-ipfs does not support localResolve option'
      }
    ]
  })

  tests.dht(defaultCommonFactory, {
    skip: [
      // dht.findpeer
      {
        name: 'should fail to find other peer if peer does not exist',
        reason: 'FIXME checking what is exactly go-ipfs returning https://github.com/ipfs/go-ipfs/issues/3862#issuecomment-294168090'
      },
      // dht.findprovs
      {
        name: 'should provide from one node and find it through another node',
        reason: 'FIXME go-ipfs endpoint doesn\'t conform with the others https://github.com/ipfs/go-ipfs/issues/5047'
      },
      // dht.get
      {
        name: 'should get a value after it was put on another node',
        reason: 'FIXME go-ipfs errors with  Error: key was not found (type 6) https://github.com/ipfs/go-ipfs/issues/3862'
      }
    ]
  })

  tests.filesRegular(defaultCommonFactory, {
    skip: [
      // .add
      isNode ? null : {
        name: 'should add a nested directory as array of tupples',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      isNode ? null : {
        name: 'should add a nested directory as array of tupples with progress',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .addPullStream
      isNode ? null : {
        name: 'should add pull stream of valid files and dirs',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .addReadableStream
      isNode ? null : {
        name: 'should add readable stream of valid files and dirs',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .addFromStream
      isNode ? null : {
        name: 'addFromStream',
        reason: 'Not designed to run in the browser'
      },
      // .addFromFs
      isNode ? null : {
        name: 'addFromFs',
        reason: 'Not designed to run in the browser'
      },
      // .addFromURL
      isNode ? null : {
        name: 'addFromURL',
        reason: 'Not designed to run in the browser'
      },
      // TODO: remove when interface-ipfs-core updated
      isNode ? null : {
        name: 'addFromUrl',
        reason: 'Not designed to run in the browser'
      },
      // .catPullStream
      {
        name: 'should export a chunk of a file',
        reason: 'TODO not implemented in go-ipfs yet'
      },
      {
        name: 'should export a chunk of a file in a Pull Stream',
        reason: 'TODO not implemented in go-ipfs yet'
      },
      {
        name: 'should export a chunk of a file in a Readable Stream',
        reason: 'TODO not implemented in go-ipfs yet'
      },
      // .get
      isNode ? null : {
        name: 'should get a directory',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .ls
      isNode ? null : {
        name: 'should ls with a base58 encoded CID',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .lsPullStream
      isNode ? null : {
        name: 'should pull stream ls with a base58 encoded CID',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .lsReadableStream
      isNode ? null : {
        name: 'should readable stream ls with a base58 encoded CID',
        reason: 'FIXME https://github.com/ipfs/js-ipfs-http-client/issues/339'
      },
      // .refs
      {
        name: 'dag refs test',
        reason: 'FIXME unskip when 0.4.21 is released'
      }
    ]
  })

  tests.filesMFS(defaultCommonFactory)

  tests.key(defaultCommonFactory, {
    skip: [
      // key.export
      {
        name: 'export',
        reason: 'TODO not implemented in go-ipfs yet'
      },
      // key.import
      {
        name: 'import',
        reason: 'TODO not implemented in go-ipfs yet'
      }
    ]
  })

  tests.miscellaneous(defaultCommonFactory, {
    skip: [
      // stop
      {
        name: 'should stop the node',
        reason: 'FIXME go-ipfs returns an error https://github.com/ipfs/go-ipfs/issues/4078'
      }
    ]
  })

  tests.name(CommonFactory.create({
    spawnOptions: {
      args: ['--offline']
    }
  }))

  // TODO: uncomment after https://github.com/ipfs/interface-ipfs-core/pull/361 being merged and a new release
  tests.namePubsub(CommonFactory.create({
    spawnOptions: {
      args: ['--enable-namesys-pubsub'],
      initOptions: { bits: 1024 }
    }
  }), {
    skip: [
      // name.pubsub.cancel
      {
        name: 'should cancel a subscription correctly returning true',
        reason: 'go-ipfs is really slow for publishing and resolving ipns records, unless in offline mode'
      },
      // name.pubsub.subs
      {
        name: 'should get the list of subscriptions updated after a resolve',
        reason: 'go-ipfs is really slow for publishing and resolving ipns records, unless in offline mode'
      }
    ]
  })

  tests.object(defaultCommonFactory)

  tests.pin(defaultCommonFactory)

  tests.ping(defaultCommonFactory, {
    skip: [
      {
        name: 'should fail when pinging an unknown peer over pull stream',
        reason: 'FIXME go-ipfs return success with text: Looking up peer <cid>'
      },
      {
        name: 'should fail when pinging peer that is not available over readable stream',
        reason: 'FIXME go-ipfs return success with text: Looking up peer <cid>'
      },
      {
        name: 'should fail when pinging a peer that is not available',
        reason: 'FIXME go-ipfs return success with text: Looking up peer <cid>'
      }
    ]
  })

  tests.pubsub(CommonFactory.create({
    spawnOptions: {
      args: ['--enable-pubsub-experiment'],
      initOptions: { bits: 1024 }
    }
  }), {
    skip: isNode ? [
      // pubsub.subscribe
      isWindows ? {
        name: 'should send/receive 100 messages',
        reason: 'FIXME https://github.com/ipfs/interface-ipfs-core/pull/188#issuecomment-354673246 and https://github.com/ipfs/go-ipfs/issues/4778'
      } : null,
      isWindows ? {
        name: 'should receive multiple messages',
        reason: 'FIXME https://github.com/ipfs/interface-ipfs-core/pull/188#issuecomment-354673246 and https://github.com/ipfs/go-ipfs/issues/4778'
      } : null
    ] : {
      reason: 'FIXME pubsub is not supported in the browser https://github.com/ipfs/js-ipfs-http-client/issues/518'
    }
  })

  tests.repo(defaultCommonFactory)

  tests.stats(defaultCommonFactory)

  tests.swarm(CommonFactory.create({
    createSetup ({ ipfsFactory, nodes }) {
      return callback => {
        callback(null, {
          spawnNode (repoPath, config, cb) {
            if (typeof repoPath === 'function') {
              cb = repoPath
              repoPath = undefined
            }

            if (typeof config === 'function') {
              cb = config
              config = undefined
            }

            const spawnOptions = { repoPath, config, initOptions: { bits: 1024, profile: 'test' } }

            ipfsFactory.spawn(spawnOptions, (err, _ipfsd) => {
              if (err) {
                return cb(err)
              }

              nodes.push(_ipfsd)
              cb(null, ipfsClient(_ipfsd.apiAddr))
            })
          }
        })
      }
    }
  }))
})
<|endoftext|>


<commit_before>/*
  Serializer to assure proper Parse-to-Ember encodings
*/
EmberParseAdapter.Serializer = DS.RESTSerializer.extend({

  primaryKey: "objectId",

  extractArray: function(store, primaryType, payload){
    var namespacedPayload = {};
    namespacedPayload[Ember.String.pluralize(primaryType.typeKey)] = payload.results;
    return this._super(store, primaryType, namespacedPayload);
  },

  extractSingle: function(store, primaryType, payload, recordId){
    var namespacedPayload = {};
    namespacedPayload[primaryType.typeKey] = payload; // this.normalize(primaryType, payload);
    return this._super(store, primaryType, namespacedPayload, recordId);
  },

  typeForRoot: function(key) {
    return Ember.String.dasherize(Ember.String.singularize(key));
  },

  /**
   * Because Parse only returns the updatedAt/createdAt values on updates
   * we have to intercept it here to assure that the adapter knows which
   * record ID we are dealing with (using the primaryKey).
   */
  extract: function(store, type, payload, id, requestType){
    if(id !== null && (requestType === "updateRecord" || requestType === "deleteRecord")){
      payload[this.get('primaryKey')] = id;
    }
    return this._super(store, type, payload, id, requestType);
  },

  /**
   * Extracts count from the payload so that you can get the total number
   * of records in Parse if you're using skip and limit.
   */
  extractMeta: function(store, type, payload) {
    if (payload && payload.count) {
      store.metaForType(type, {count: payload.count});
      delete payload.count;
    }
  },

  /**
   * Special handling for the Date objects inside the properties of
   * Parse responses.
   */
  normalizeAttributes: function(type, hash){
    type.eachAttribute(function(key, meta){
      if(meta.type === "date" && Ember.typeOf(hash[key]) === "object" && hash[key].iso){
        hash[key] = hash[key].iso; //new Date(hash[key].iso).toISOString();
      }
    });
    this._super(type, hash);
  },

  /**
   * Special handling of the Parse relation types. In certain
   * conditions there is a secondary query to retrieve the "many"
   * side of the "hasMany".
   */
  normalizeRelationships: function(type, hash){
    var store = this.get('store');
    var serializer = this;

    type.eachRelationship(function(key, relationship) {

      var options = relationship.options;

      // Handle the belongsTo relationships
      if(hash[key] && relationship.kind === 'belongsTo'){
        hash[key] = hash[key].objectId;
      }

      // Handle the hasMany relationships
      if(hash[key] && relationship.kind === 'hasMany'){

        // If this is a Relation hasMany then we need to supply
        // the links property so the adapter can async call the
        // relationship.
        // The adapter findHasMany has been overridden to make use of this.
        if(options.relation) {
          // hash[key] contains the response of Parse.com: eg {__type: Relation, className: MyParseClassName}
          // this is an object that make ember-data fail, as it expects nothing or an array ids that represent the records
          hash[key] = [];

          // ember-data expects the link to be a string
          // The adapter findHasMany will parse it
          hash.links = {};
          hash.links[key] = JSON.stringify({type: relationship.type, key: key});
        }

        if(options.array){
          // Parse will return [null] for empty relationships
          if(hash[key].length && hash[key]){
            hash[key].forEach(function(item, index, items){
              // When items are pointers we just need the id
              // This occurs when request was made without the include query param.
              if(item.__type === "Pointer"){
                items[index] = item.objectId;
              } else {
                // When items are objects we need to clean them and add them to the store.
                // This occurs when request was made with the include query param.
                delete item.__type;
                delete item.className;
                item.id = item.objectId;
                delete item.objectId;
                item.type = relationship.type;
                serializer.normalizeAttributes(relationship.type, item);
                serializer.normalizeRelationships(relationship.type, item);
                store.push(relationship.type, item);
              }
            });
          }
        }

      }
    }, this);

    this._super(type, hash);
  },

  serializeIntoHash: function(hash, type, snapshot, options){
    Ember.merge(hash, this.serialize(snapshot, options));
  },

  serializeAttribute: function(snapshot, json, key, attribute) {
    // These are Parse reserved properties and we won't send them.
    if( key === 'createdAt' ||
        key === 'updatedAt' ||
        key === 'emailVerified' ||
        key === 'sessionToken' ){
      delete json[key];
    } else {
      this._super(snapshot, json.attributes, key, attribute);
    }
  },

  serializeBelongsTo: function(snapshot, json, relationship){
    var key = relationship.key;
    var belongsTo = snapshot.belongsTo(key);
    if(belongsTo){
      // TODO: Perhaps this is working around a bug in Ember-Data? Why should
      // promises be returned here.
      if (belongsTo instanceof DS.PromiseObject) {
        if (!belongsTo.attr('isFulfilled')) {
          throw new Error("belongsTo values *must* be fulfilled before attempting to serialize them");
        }
        belongsTo = belongsTo.attr('content');
      }

      json[key] = {
        "__type": "Pointer",
        "className": this.parseClassName(belongsTo.constructor.typeKey),
        "objectId": belongsTo.attr('id')
      };
    }
  },

  parseClassName: function(key) {
    if (key === "parseUser") {
      return "_User";
    } else {
      return Ember.String.capitalize(Ember.String.camelize(key));
    }
  },

  serializeHasMany: function(snapshot, json, relationship){
    var key = relationship.key;
    var hasMany = snapshot.hasMany(key);
    var options = relationship.options;
    if(hasMany && hasMany.attr('length') > 0){

      json[key] = { "objects": [] };

      if(options.relation){
        json[key].__op = "AddRelation";
      }

      if(options.array){
        json[key].__op = "AddUnique";
      }

      var _this = this;

      hasMany.forEach(function(child){
        json[key].objects.push({
          "__type": "Pointer",
          "className": _this.parseClassName(child.constructor.typeKey),
          "objectId": child.attr('id')
        });
      });

      if(hasMany._deletedItems && hasMany._deletedItems.length){
        if(options.relation){
          var addOperation = json[key];
          var deleteOperation = { "__op": "RemoveRelation", "objects": [] };
          hasMany._deletedItems.forEach(function(item){
            deleteOperation.objects.push({
              "__type": "Pointer",
              "className": item.type,
              "objectId": item.id
            });
          });
          json[key] = { "__op": "Batch", "ops": [addOperation, deleteOperation] };
        }
        if(options.array){
          json[key].deleteds = { "__op": "Remove", "objects": [] };
          hasMany._deletedItems.forEach(function(item){
            json[key].deleteds.objects.push({
              "__type": "Pointer",
              "className": item.type,
              "objectId": item.id
            });
          });
        }
      }
    } else {
      json[key] = [];
    }
  }

});
<commit_msg>fixed "serializeAttribute": fed _super with json.attributes, probably due to a bad read of the ember-data document example. Here, we do not create the attribute "attributes" into "json" object, we just delete the protected Parse keys<commit_after>/*
  Serializer to assure proper Parse-to-Ember encodings
*/
EmberParseAdapter.Serializer = DS.RESTSerializer.extend({

  primaryKey: "objectId",

  extractArray: function(store, primaryType, payload){
    var namespacedPayload = {};
    namespacedPayload[Ember.String.pluralize(primaryType.typeKey)] = payload.results;
    return this._super(store, primaryType, namespacedPayload);
  },

  extractSingle: function(store, primaryType, payload, recordId){
    var namespacedPayload = {};
    namespacedPayload[primaryType.typeKey] = payload; // this.normalize(primaryType, payload);
    return this._super(store, primaryType, namespacedPayload, recordId);
  },

  typeForRoot: function(key) {
    return Ember.String.dasherize(Ember.String.singularize(key));
  },

  /**
   * Because Parse only returns the updatedAt/createdAt values on updates
   * we have to intercept it here to assure that the adapter knows which
   * record ID we are dealing with (using the primaryKey).
   */
  extract: function(store, type, payload, id, requestType){
    if(id !== null && (requestType === "updateRecord" || requestType === "deleteRecord")){
      payload[this.get('primaryKey')] = id;
    }
    return this._super(store, type, payload, id, requestType);
  },

  /**
   * Extracts count from the payload so that you can get the total number
   * of records in Parse if you're using skip and limit.
   */
  extractMeta: function(store, type, payload) {
    if (payload && payload.count) {
      store.metaForType(type, {count: payload.count});
      delete payload.count;
    }
  },

  /**
   * Special handling for the Date objects inside the properties of
   * Parse responses.
   */
  normalizeAttributes: function(type, hash){
    type.eachAttribute(function(key, meta){
      if(meta.type === "date" && Ember.typeOf(hash[key]) === "object" && hash[key].iso){
        hash[key] = hash[key].iso; //new Date(hash[key].iso).toISOString();
      }
    });
    this._super(type, hash);
  },

  /**
   * Special handling of the Parse relation types. In certain
   * conditions there is a secondary query to retrieve the "many"
   * side of the "hasMany".
   */
  normalizeRelationships: function(type, hash){
    var store = this.get('store');
    var serializer = this;

    type.eachRelationship(function(key, relationship) {

      var options = relationship.options;

      // Handle the belongsTo relationships
      if(hash[key] && relationship.kind === 'belongsTo'){
        hash[key] = hash[key].objectId;
      }

      // Handle the hasMany relationships
      if(hash[key] && relationship.kind === 'hasMany'){

        // If this is a Relation hasMany then we need to supply
        // the links property so the adapter can async call the
        // relationship.
        // The adapter findHasMany has been overridden to make use of this.
        if(options.relation) {
          // hash[key] contains the response of Parse.com: eg {__type: Relation, className: MyParseClassName}
          // this is an object that make ember-data fail, as it expects nothing or an array ids that represent the records
          hash[key] = [];

          // ember-data expects the link to be a string
          // The adapter findHasMany will parse it
          hash.links = {};
          hash.links[key] = JSON.stringify({type: relationship.type, key: key});
        }

        if(options.array){
          // Parse will return [null] for empty relationships
          if(hash[key].length && hash[key]){
            hash[key].forEach(function(item, index, items){
              // When items are pointers we just need the id
              // This occurs when request was made without the include query param.
              if(item.__type === "Pointer"){
                items[index] = item.objectId;
              } else {
                // When items are objects we need to clean them and add them to the store.
                // This occurs when request was made with the include query param.
                delete item.__type;
                delete item.className;
                item.id = item.objectId;
                delete item.objectId;
                item.type = relationship.type;
                serializer.normalizeAttributes(relationship.type, item);
                serializer.normalizeRelationships(relationship.type, item);
                store.push(relationship.type, item);
              }
            });
          }
        }

      }
    }, this);

    this._super(type, hash);
  },

  serializeIntoHash: function(hash, type, snapshot, options){
    Ember.merge(hash, this.serialize(snapshot, options));
  },

  serializeAttribute: function(snapshot, json, key, attribute) {
    // These are Parse reserved properties and we won't send them.
    if( key === 'createdAt' ||
        key === 'updatedAt' ||
        key === 'emailVerified' ||
        key === 'sessionToken' ){
      delete json[key];
    } else {
      this._super(snapshot, json, key, attribute);
    }
  },

  serializeBelongsTo: function(snapshot, json, relationship){
    var key = relationship.key;
    var belongsTo = snapshot.belongsTo(key);
    if(belongsTo){
      // TODO: Perhaps this is working around a bug in Ember-Data? Why should
      // promises be returned here.
      if (belongsTo instanceof DS.PromiseObject) {
        if (!belongsTo.attr('isFulfilled')) {
          throw new Error("belongsTo values *must* be fulfilled before attempting to serialize them");
        }
        belongsTo = belongsTo.attr('content');
      }

      json[key] = {
        "__type": "Pointer",
        "className": this.parseClassName(belongsTo.constructor.typeKey),
        "objectId": belongsTo.attr('id')
      };
    }
  },

  parseClassName: function(key) {
    if (key === "parseUser") {
      return "_User";
    } else {
      return Ember.String.capitalize(Ember.String.camelize(key));
    }
  },

  serializeHasMany: function(snapshot, json, relationship){
    var key = relationship.key;
    var hasMany = snapshot.hasMany(key);
    var options = relationship.options;
    if(hasMany && hasMany.attr('length') > 0){

      json[key] = { "objects": [] };

      if(options.relation){
        json[key].__op = "AddRelation";
      }

      if(options.array){
        json[key].__op = "AddUnique";
      }

      var _this = this;

      hasMany.forEach(function(child){
        json[key].objects.push({
          "__type": "Pointer",
          "className": _this.parseClassName(child.constructor.typeKey),
          "objectId": child.attr('id')
        });
      });

      if(hasMany._deletedItems && hasMany._deletedItems.length){
        if(options.relation){
          var addOperation = json[key];
          var deleteOperation = { "__op": "RemoveRelation", "objects": [] };
          hasMany._deletedItems.forEach(function(item){
            deleteOperation.objects.push({
              "__type": "Pointer",
              "className": item.type,
              "objectId": item.id
            });
          });
          json[key] = { "__op": "Batch", "ops": [addOperation, deleteOperation] };
        }
        if(options.array){
          json[key].deleteds = { "__op": "Remove", "objects": [] };
          hasMany._deletedItems.forEach(function(item){
            json[key].deleteds.objects.push({
              "__type": "Pointer",
              "className": item.type,
              "objectId": item.id
            });
          });
        }
      }
    } else {
      json[key] = [];
    }
  }

});
<|endoftext|>


<commit_before><commit_msg>mock trail<commit_after>'use strict';

const faker = require('faker');
const Trail = require('../../model/trail.js');

const mockTrail = module.exports = {};

mockTrail.mockOne = () => {
  return new Trail({
    trailName: faker.lorem.word(),
    mapURI: faker.image.nature(),
    difficulty: 'Hard',
    type: 'Down Hill',
    distance: faker.random.number() + ' Miles',
    elevation: faker.random.number() + ' Feet',
    lat: faker.address.latitude(),
    long: faker.address.longitude(),
    zoom: 3,
    comments: [],
  });
};
<|endoftext|>