<commit_before>'use babel';
/* @flow */

import { CompositeDisposable } from 'atom';
import path from 'path';

import handleData from './message.js';
// import * as servers from './servers.js';

import type { LinterMessage } from './message';

type BufferType = {
  cachedText: string;
  getText(): string;
}

type TextEditorType = {
  getPath(): string;
  buffer: BufferType;
  isModified(): boolean;
}

type Linter = {
  grammarScopes: Array<string>;
  scope: 'file' | 'project';
  name?: string;
  lintOnFly: boolean;
  lint(TextEditor: TextEditorType): Array<LinterMessage> | Promise<Array<LinterMessage>>;
};

export default {
  config: {
    executablePath: {
      type: 'string',
      default: 'flow',
      description: 'Absolute path to the Flow executable on your system.',
    },
    enableAll: {
      type: 'boolean',
      default: false,
      description: 'Typecheck all files, not just @flow',
    },
  },

  activate(): void {
    require('atom-package-deps').install('linter-flow');

    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(atom.config.observe('linter-flow.executablePath', (pathToFlow) => {
      this.pathToFlow = pathToFlow;
    }));
    this.subscriptions.add(atom.config.observe('linter-flow.enableAll', (enableAll) => {
      this.enableAll = enableAll;
    }));
  },

  deactivate(): void {
    // servers.stop();
    this.subscriptions.dispose();
  },

  provideLinter(): Linter {
    const helpers = require('atom-linter');

    return {
      grammarScopes: [
        'source.js',
        'source.js.jsx',
        'source.babel',
        'source.js-semantic',
        'source.es6',
      ],
      scope: 'project',
      name: 'Flow',
      lintOnFly: true,
      lint: (TextEditor) => {
        const filePath = TextEditor.getPath();
        const fileText = TextEditor.buffer.cachedText;

        // Is flow enabled for current file ?
        if (fileText.indexOf('@flow') === -1 && !this.enableAll) {
          return [];
        }

        // Check if .flowconfig file is present
        const flowConfig = helpers.find(filePath, '.flowconfig');
        if (!flowConfig) {
          atom.notifications.addWarning('[Linter-Flow] Missing .flowconfig file.', {
            detail: 'To get started with Flow, run `flow init`.',
            dismissable: true,
          });
          return [];
        }

        let args;
        let options;

        // Use `check-contents` for unsaved files. and `status` for saved files.
        // if (TextEditor.isModified()) {
        //   args = ['check-contents', '--json', filePath];
        //   options = { cwd: path.dirname(filePath), stdin: fileText };
        // } else {
        args = ['status', '--json', filePath];
        options = { cwd: path.dirname(filePath) };
        // }

        // return servers.start(this.pathToFlow, flowConfig, this.enableAll).then(() =>
        return helpers
          .exec(this.pathToFlow, args, options)
          .then(JSON.parse)
          .then(handleData);
        // );
      },
    };
  },
};
<commit_msg>fix(servers): use check-contents not status<commit_after>'use babel';
/* @flow */

import { CompositeDisposable } from 'atom';
import path from 'path';

import handleData from './message.js';
// import * as servers from './servers.js';

import type { LinterMessage } from './message';

type BufferType = {
  cachedText: string;
  getText(): string;
}

type TextEditorType = {
  getPath(): string;
  buffer: BufferType;
  isModified(): boolean;
}

type Linter = {
  grammarScopes: Array<string>;
  scope: 'file' | 'project';
  name?: string;
  lintOnFly: boolean;
  lint(TextEditor: TextEditorType): Array<LinterMessage> | Promise<Array<LinterMessage>>;
};

export default {
  config: {
    executablePath: {
      type: 'string',
      default: 'flow',
      description: 'Absolute path to the Flow executable on your system.',
    },
    enableAll: {
      type: 'boolean',
      default: false,
      description: 'Typecheck all files, not just @flow',
    },
  },

  activate(): void {
    require('atom-package-deps').install('linter-flow');

    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(atom.config.observe('linter-flow.executablePath', (pathToFlow) => {
      this.pathToFlow = pathToFlow;
    }));
    this.subscriptions.add(atom.config.observe('linter-flow.enableAll', (enableAll) => {
      this.enableAll = enableAll;
    }));
  },

  deactivate(): void {
    // servers.stop();
    this.subscriptions.dispose();
  },

  provideLinter(): Linter {
    const helpers = require('atom-linter');

    return {
      grammarScopes: [
        'source.js',
        'source.js.jsx',
        'source.babel',
        'source.js-semantic',
        'source.es6',
      ],
      scope: 'project',
      name: 'Flow',
      lintOnFly: true,
      lint: (TextEditor) => {
        const filePath = TextEditor.getPath();
        const fileText = TextEditor.buffer.cachedText;

        // Is flow enabled for current file ?
        if (fileText.indexOf('@flow') === -1 && !this.enableAll) {
          return [];
        }

        // Check if .flowconfig file is present
        const flowConfig = helpers.find(filePath, '.flowconfig');
        if (!flowConfig) {
          atom.notifications.addWarning('[Linter-Flow] Missing .flowconfig file.', {
            detail: 'To get started with Flow, run `flow init`.',
            dismissable: true,
          });
          return [];
        }

        let args;
        let options;

        // Use `check-contents` for unsaved files. and `status` for saved files.
        // if (TextEditor.isModified()) {
        args = ['check-contents', '--json', filePath];
        options = { cwd: path.dirname(filePath), stdin: fileText };
        // } else {
        // args = ['status', '--json', filePath];
        // options = { cwd: path.dirname(filePath) };
        // }

        // return servers.start(this.pathToFlow, flowConfig, this.enableAll).then(() =>
        return helpers
          .exec(this.pathToFlow, args, options)
          .then(JSON.parse)
          .then(handleData);
        // );
      },
    };
  },
};
<|endoftext|>


<commit_before>const Request = require('./request')
const trackRoot = 'https://track.customer.io/api/v1'
const apiRoot = 'https://api.customer.io/v1/api'

const BROADCASTS_ALLOWED_RECIPIENT_FIELDS = {
  ids: ['ids', 'id_ignore_missing'],
  emails: ['emails', 'email_ignore_missing', 'email_add_duplicates'],
  per_user_data: ['per_user_data'],
  data_file_url: ['data_file_url']
};

const filterRecipientsDataForField = (recipients, field) => {
  return BROADCASTS_ALLOWED_RECIPIENT_FIELDS[field]
    .reduce((obj, field) => Object.assign(obj, { [field]: recipients[field] }), {});
};

module.exports = class CustomerIO {
  constructor(siteid, apikey) {
    this.siteid = siteid
    this.apikey = apikey
    this.request = new Request(this.siteid, this.apikey)
  }

  identify(id, data = {}) {
    return this.request.put(`${trackRoot}/customers/${id}`, data)
  }

  destroy(id) {
    return this.request.destroy(`${trackRoot}/customers/${id}`)
  }

  track(id, data = {}) {
    return this.request.post(`${trackRoot}/customers/${id}/events`, data)
  }

  trackAnonymous(data = {}) {
    return this.request.post(`${trackRoot}/events`, data)
  }

  trackPageView(id, path) {
    return this.request.post(`${trackRoot}/customers/${id}/events`, {
      type: 'page',
      name: path
    })
  }

  addDevice(id, device_id, platform, data = {}) {
    return this.request.put(`${trackRoot}/customers/${id}/devices`, {
      device: Object.assign({ id: device_id, platform }, data)
    })
  }

  deleteDevice(id, token) {
    return this.request.destroy(`${trackRoot}/customers/${id}/devices/${token}`);
  }

  triggerBroadcast(id, data, recipients) {
    let payload = {};
    let customRecipientField =
      Object
      .keys(BROADCASTS_ALLOWED_RECIPIENT_FIELDS)
      .find(field => recipients[field]);

    if (customRecipientField) {
      payload = Object.assign({ data }, filterRecipientsDataForField(recipients, customRecipientField));
    } else {
      payload = {
        data,
        recipients
      };
    }

    return this.request.post(`${apiRoot}/campaigns/${id}/triggers`, payload)
  }

  addToSegment(segmentId, customerIds = []) {
    return this.request.post(`${trackRoot}/segments/${segmentId}/add_customers`, {
      ids: customerIds
    })
  }

  removeFromSegment(segmentId, customerIds = []) {
    return this.request.post(`${trackRoot}/segments/${segmentId}/remove_customers`, {
      ids: customerIds
    })
  }
}
<commit_msg>Improve reducer clarity<commit_after>const Request = require('./request')
const trackRoot = 'https://track.customer.io/api/v1'
const apiRoot = 'https://api.customer.io/v1/api'

const BROADCASTS_ALLOWED_RECIPIENT_FIELDS = {
  ids: ['ids', 'id_ignore_missing'],
  emails: ['emails', 'email_ignore_missing', 'email_add_duplicates'],
  per_user_data: ['per_user_data'],
  data_file_url: ['data_file_url']
}

const filterRecipientsDataForField = (recipients, field) => {
  return BROADCASTS_ALLOWED_RECIPIENT_FIELDS[field]
    .reduce((obj, field) => {
      obj[field] = recipients[field]
      return obj
    })
}

module.exports = class CustomerIO {
  constructor(siteid, apikey) {
    this.siteid = siteid
    this.apikey = apikey
    this.request = new Request(this.siteid, this.apikey)
  }

  identify(id, data = {}) {
    return this.request.put(`${trackRoot}/customers/${id}`, data)
  }

  destroy(id) {
    return this.request.destroy(`${trackRoot}/customers/${id}`)
  }

  track(id, data = {}) {
    return this.request.post(`${trackRoot}/customers/${id}/events`, data)
  }

  trackAnonymous(data = {}) {
    return this.request.post(`${trackRoot}/events`, data)
  }

  trackPageView(id, path) {
    return this.request.post(`${trackRoot}/customers/${id}/events`, {
      type: 'page',
      name: path
    })
  }

  addDevice(id, device_id, platform, data = {}) {
    return this.request.put(`${trackRoot}/customers/${id}/devices`, {
      device: Object.assign({ id: device_id, platform }, data)
    })
  }

  deleteDevice(id, token) {
    return this.request.destroy(`${trackRoot}/customers/${id}/devices/${token}`)
  }

  triggerBroadcast(id, data, recipients) {
    let payload = {}
    let customRecipientField =
      Object
      .keys(BROADCASTS_ALLOWED_RECIPIENT_FIELDS)
      .find(field => recipients[field])

    if (customRecipientField) {
      payload = Object.assign({ data }, filterRecipientsDataForField(recipients, customRecipientField))
    } else {
      payload = {
        data,
        recipients
      };
    }

    return this.request.post(`${apiRoot}/campaigns/${id}/triggers`, payload)
  }

  addToSegment(segmentId, customerIds = []) {
    return this.request.post(`${trackRoot}/segments/${segmentId}/add_customers`, {
      ids: customerIds
    })
  }

  removeFromSegment(segmentId, customerIds = []) {
    return this.request.post(`${trackRoot}/segments/${segmentId}/remove_customers`, {
      ids: customerIds
    })
  }
}
<|endoftext|>


<commit_before>nfcRing.heatmap = {
  coOrds: {}, // The Co-Ordinates we have stored for this phone
  coOrdData: {
    data: []
  },

  init: function(){

    nfcRing.heatmap.loadFromRemote(function(){

      if($('#heatMap canvas').length >= 1){
        console.log("Heatmap already drawn");
        return;
      }

      // Initialize the heatmap
      nfcRing.heatmap.config = { // Our heatmap config
        element: document.getElementById("heatMap"),
        radius: 30,
        opacity: 100
      }

      nfcRing.heatmap.coOrdData = {};
      nfcRing.heatmap.coOrdData.max = 20;
      nfcRing.heatmap.coOrdData.data = [];

      $.each(nfcRing.heatmap.coOrds, function(k,v){
        var x = k.split(":")[0];
        var y = k.split(":")[1];
        x = Number(x);
        y = Number(y);
        if(x >= 0 && y >= 0){
          var coOrd = {
            x: x,
            y: y,
            count: v*10
          };
          nfcRing.heatmap.coOrdData.data.push(coOrd);
        }
      });

      console.log("1. initiating heatmap");
      window.hm = h337.create(nfcRing.heatmap.config);
      console.log("2. Writing data to heatmap", nfcRing.heatmap.coOrdData);
      window.hm.store.setDataSet(nfcRing.heatmap.coOrdData);
      console.log("3. Done writing data to the heatmap");
    });
  },

  draw: function(){ // Draw the data from our coOrds onto the heatmap

  },

  loadFromRemote: function(callback){ // Getting data from Remote database..

    try{
      if(!device){return false;}
    }catch(e){
      return false;
    }

    var coOrdinateCounter = {};
    var model = device.model;

    $.getJSON("http://sweetspot.nfcring.com/api/v1/sweetspot?model="+model).done(function(results){
      results = JSON.parse(results);
      for (var i = 0; i < results.length; i++) {
        var object = results[i];
        var x = object.x; // 1
        var y = object.y; // 2

        // Turns it into a counted set of objects instead of single objects
        if(coOrdinateCounter[x+":"+y]){ // If this coOrdinateCounter exists add to it
          coOrdinateCounter[x+":"+y] = coOrdinateCounter[x+":"+y] + 1;
        }else{
          coOrdinateCounter[x+":"+y] = 1;
        }
      }
      console.log("Got results from database", coOrdinateCounter);

      if(results.length == 0){ // if there are no results
        console.log("no results from database");
      }else{ // there are some heatmap results so let's draw em
        console.log("0. Drawing heatmap");
        if($('#heatMap canvas').length < 1){
          nfcRing.heatmap.coOrds = coOrdinateCounter;
        }
        // nfcRing.drawHeatMap();
        callback();
      }

    });
  },

  sendToRemote: function(x,y,model){
    console.log("Posting to remote");
    $.post("http://sweetspot.nfcring.com/api/v1/sweetspot?model="+model+"&x="+x+"&y="+y).done(function(results){
      alert(html10n.get("sweetSpot.yay"), false, html10n.get("sweetSpot.done"));
      nfcRing.ui.displayPage("index"); // Return user back to start page
    }).fail(function(){
      alert("Failed to share sweet spot location :(  Check your Internet connectivity"); // TODO i18n me
      nfcRing.ui.displayPage("index");
    });
  }
}
<commit_msg>introduce caching layer!<commit_after>nfcRing.heatmap = {
  coOrds: {}, // The Co-Ordinates we have stored for this phone
  coOrdData: {
    data: []
  },

  init: function(){

    nfcRing.heatmap.loadFromRemote(function(){

      if($('#heatMap canvas').length >= 1){
        console.log("Heatmap already drawn");
        return;
      }

      // Initialize the heatmap
      nfcRing.heatmap.config = { // Our heatmap config
        element: document.getElementById("heatMap"),
        radius: 30,
        opacity: 100
      }

      nfcRing.heatmap.coOrdData = {};
      nfcRing.heatmap.coOrdData.max = 20;
      nfcRing.heatmap.coOrdData.data = [];

      $.each(nfcRing.heatmap.coOrds, function(k,v){
        var x = k.split(":")[0];
        var y = k.split(":")[1];
        x = Number(x);
        y = Number(y);
        if(x >= 0 && y >= 0){
          var coOrd = {
            x: x,
            y: y,
            count: v*10
          };
          nfcRing.heatmap.coOrdData.data.push(coOrd);
        }
      });

      console.log("1. initiating heatmap");
      window.hm = h337.create(nfcRing.heatmap.config);
      console.log("2. Writing data to heatmap", nfcRing.heatmap.coOrdData);
      window.hm.store.setDataSet(nfcRing.heatmap.coOrdData);
      console.log("3. Done writing data to the heatmap");
    });
  },

  draw: function(){ // Draw the data from our coOrds onto the heatmap

  },

  loadFromRemote: function(callback){ // Getting data from Remote database..

    try{
      if(!device){return false;}
    }catch(e){
      return false;
    }

    var coOrdinateCounter = {};
    var model = device.model;

    $.getJSON("http://sweetspot.nfcring.com/api/v1/sweetspot?model="+model).done(function(results){
      results = JSON.parse(results);
      for (var i = 0; i < results.length; i++) {
        var object = results[i];
        var x = object.x; // 1
        var y = object.y; // 2

        // Turns it into a counted set of objects instead of single objects
        if(coOrdinateCounter[x+":"+y]){ // If this coOrdinateCounter exists add to it
          coOrdinateCounter[x+":"+y] = coOrdinateCounter[x+":"+y] + 1;
        }else{
          coOrdinateCounter[x+":"+y] = 1;
        }
      }
      console.log("Got results from database", coOrdinateCounter);

      if(results.length == 0){ // if there are no results
        console.log("no results from database");
      }else{ // there are some heatmap results so let's draw em
        console.log("0. Drawing heatmap");
        if($('#heatMap canvas').length < 1){
          nfcRing.heatmap.coOrds = coOrdinateCounter;
          localStorage.setItem("heatMapCache", JSON.stringify(nfcRing.heatmap.coOrds));
        }
        // nfcRing.drawHeatMap();
        callback();
      }

    }).fail(function(){
      console.log("Attempting to load data from cache");
      var cachedCoOrds = localStorage.getItem("heatMapCache");
      if(cachedCoOrds){
        nfcRing.heatmap.coOrds = JSON.parse(cachedCoOrds);
        callback();
      }
    });
  },

  sendToRemote: function(x,y,model){
    console.log("Posting to remote");
    $.post("http://sweetspot.nfcring.com/api/v1/sweetspot?model="+model+"&x="+x+"&y="+y).done(function(results){
      alert(html10n.get("sweetSpot.yay"), false, html10n.get("sweetSpot.done"));
      nfcRing.ui.displayPage("index"); // Return user back to start page
    }).fail(function(){
      alert("Failed to share sweet spot location :(  Check your Internet connectivity"); // TODO i18n me
      nfcRing.ui.displayPage("index");
    });
  }
}
<|endoftext|>


<commit_before><commit_msg>default task for gulp added<commit_after>'use strict';

var gulp = require('gulp');

gulp.task('default', function() {
	// place code for your default task here
});

<|endoftext|>


<commit_before>var async = require('async');
var naan = require('naan');
var _ = require('underscore');
var util = require('util');

exports.create = function(label, keys, callback) {
  if (!Array.isArray(keys)) keys = [keys];

  label = encodeURIComponent(label);
  var body = { property_keys: keys };

  var endpoint = util.format('schema/index/%s', label);
  var op = this.operation(endpoint, 'POST', body);
  this.call(op, function(err, index) {
    if (err) callback(err);
    else callback(null, index);
  });
};

exports.indexes = function(label, callback) {
  label = encodeURIComponent(label);
  var endpoint = util.format('schema/index/%s', label);
  var op = this.operation(endpoint, 'GET');
  this.call(op, function(err, indexes) {
    if (err) callback(err);
    else callback(null, indexes);
  });
};
<commit_msg>neo4j-2 indexes: add implementation for dropping an index<commit_after>var async = require('async');
var naan = require('naan');
var _ = require('underscore');
var util = require('util');

// although it looks like this will support compound keys, neo4j-2 doesn't yet,
// so attempting to create one will just give you an error from neo4j.
exports.create = function(label, keys, callback) {
  if (!Array.isArray(keys)) keys = [keys];

  label = encodeURIComponent(label);
  var body = { property_keys: keys };

  var endpoint = util.format('schema/index/%s', label);
  var op = this.operation(endpoint, 'POST', body);
  this.call(op, function(err, index) {
    if (err) callback(err);
    else callback(null, index);
  });
};

exports.indexes = function(label, callback) {
  label = encodeURIComponent(label);
  var endpoint = util.format('schema/index/%s', label);
  var op = this.operation(endpoint, 'GET');
  this.call(op, function(err, indexes) {
    if (err) callback(err);
    else callback(null, indexes);
  });
};

exports.drop = function(label, key, callback) {
  label = encodeURIComponent(label);
  key = encodeURIComponent(key);
  var endpoint = util.format('schema/index/%s/%s', label, key);
  var op = this.operation(endpoint, 'DELETE');
  this.call(op, function(err) {
    if (err) callback(err);
    else callback();
  });
}
<|endoftext|>


<commit_before>var lnklib = require('../build/Release/lnklib.node');

function LibraryModule()
{
	this.id = undefined;
	this.filepath = undefined;
	this.functions = [];

	if(arguments.length > 0) {
		this.load.apply(this, arguments);
	}
}

LibraryModule.prototype.load = function(filepath) {
	if(this.id) {
		this.close();
	}
	this.id = lnklib.load(filepath);
	this.filepath = filepath;
};

LibraryModule.prototype.close = function() {
	if(this.id) {
		for(var i in this.functions) {
			lnklib.clearFunction(this.functions[i].id);
		}

		return lnklib.unload(this.id);
	}
	return false;
};

LibraryModule.prototype._getLinkId = function(identifier) {
	for(var i in this.functions) {
		if(this.functions[i].identifier == identifier) {
			return this.functions[i].id;
		}
	}
	return 0;
};

LibraryModule.prototype.linkFunction = function(identifier) {
	var id = this._getLinkId(identifier);
	if(id === 0) {
		id = lnklib.getFunction(this.id, identifier);

		this.functions.push({
			id: id,
			identifier: identifier
		});
	}

	return function() {
		console.log('TODO: Call function');
	}
};

module.exports = LibraryModule;<commit_msg>Need to reset internal variables after closing a module<commit_after>var lnklib = require('../build/Release/lnklib.node');

function LibraryModule()
{
	this._init();

	if(arguments.length > 0) {
		this.load.apply(this, arguments);
	}
}

LibraryModule.prototype._init = function() {
	this.id = undefined;
	this.filepath = undefined;
	this.functions = [];
}

LibraryModule.prototype.load = function(filepath) {
	if(this.id) {
		this.close();
	}
	this.id = lnklib.load(filepath);
	this.filepath = filepath;
};

LibraryModule.prototype.close = function() {
	if(this.id) {
		for(var i in this.functions) {
			lnklib.clearFunction(this.functions[i].id);
		}

		var result = lnklib.unload(this.id);
		this._init();
		return result;
	}
	return false;
};

LibraryModule.prototype._getLinkId = function(identifier) {
	for(var i in this.functions) {
		if(this.functions[i].identifier == identifier) {
			return this.functions[i].id;
		}
	}
	return 0;
};

LibraryModule.prototype.linkFunction = function(identifier) {
	var id = this._getLinkId(identifier);
	if(id === 0) {
		id = lnklib.getFunction(this.id, identifier);

		this.functions.push({
			id: id,
			identifier: identifier
		});
	}

	return function() {
		console.log('TODO: Call function');
	}
};

module.exports = LibraryModule;<|endoftext|>


<commit_before>'use strict';

/*****************************************
 * setup
 */

/*****************************************
 * copy ssh key
 * cat ~/.ssh/id_rsa.pub | ssh wifibox 'cat >> /etc/dropbear/authorized_keys'
 *
 * make global executable node npm package
 * http://www.anupshinde.com/posts/how-to-create-nodejs-npm-package/
 */

//--requires
var chokidar = require('chokidar');
var scp = require('scp');
var exec = require('ssh-exec');
var fs = require('fs');
var jsesc = require('jsesc');
var program = program = require('commander');
//var config = require('config');

//--export
module.exports = ScpSync;

//--console
var log = console.log.bind(console);

//--vars
var settings = {
  sourcepath: undefined,
  destinationpath: undefined,
  user: undefined,
  remoteip: undefined,
  hostname: undefined
}

/*****************************************
 * main
 */
function ScpSync() {
  if (!(this instanceof ScpSync)) return new ScpSync();

  var self = this;

  //--init cli
  this.init(function() {
    //--initial transfer of files from source to remote dir
    self.transfer('.');

    //--setup watcher
    self.watcher = chokidar.watch('.', {
      ignored: /[\/\\]\./,
      persistent: true,
      cwd: settings.sourcepath,
      ignoreInitial: true
    });

    //--watcher events
    self.watcher
      .on('change', self.transfer)
      .on('add', self.transfer)
      .on('unlink', self.remove)
      // More events.
      .on('addDir', self.transfer)
      .on('unlinkDir', self.remove)
      .on('error', function(error) {
        log('error: ', error);
      })
      .on('ready', function() {
        log('Initial scan complete. Ready for changes...');
      })
      .on('raw', function(event, path, details) {
        //log('Raw event info:', event, path, details);
      });
  });
}

/*****************************************
 * functions
 */
ScpSync.prototype.init = function(cb) {
  var self = this;

  //--program setup
  program
    .version('1.0.0')
    .usage('[options] [dir]')
    .option('-s, --sourcepath <sourcepath>', 'specify source folder')
    .option('-d, --destination <destination>', 'specify destination folder')
    .option('-u, --user <user>', 'specifiy remote user name')
    .option('-i, --remoteip <remoteip>', 'specifiy host ip x.x.x.x')
    .option('-n, --hostname <hostname>', 'specifiy ssh hostname')
    .parse(process.argv);

  //--source
  if (program.sourcepath) {
    settings.sourcepath = program.sourcepath;
    log('source:', settings.sourcepath);
  } else {
    console.error("no source specified", settings.sourcepath);
    return 1;
  }

  //--destination
  if (program.destination) {
    settings.destinationpath = program.destination;
    log('destination:', settings.destinationpath);
  } else {
    console.error("no destination specified");
    return 1;
  }

  //--user
  if (program.user) {
    settings.user = program.user;
    log('user:', settings.user);
  } else {
    console.error("no user specified");
    return 1;
  }

  //--hostip
  if (program.remoteip) {
    settings.remoteip = program.remoteip;
    log('remoteip:', settings.remoteip);
  } else {
    console.error("no remoteip specified");
    return 1;
  }

  //--hostname
  if (program.hostname) {
    settings.hostname = program.hostname;
    log('hostname:', settings.hostname);
  } else {
    console.error("no hostname specified");
    return 1;
  }

  //--make sure destination path exists
  var cmd = 'mkdir -p ' + settings.destinationpath;
  log('[note] mkdir cmd: ', cmd);

  var mkdir = exec(cmd, {
    user: settings.user,
    host: settings.remoteip,
  }).pipe(process.stdout);

  //--wait some seconds for mkdir -p to have completed
  setTimeout(function() {
    return cb();
  }, 3000);
};

ScpSync.prototype.transfer = function(filepath) {
  var self = this;
  log('[note] transfer: ', settings.sourcepath + filepath);

  if (filepath === '') {
    filepath = '.';
  }

  var options = {
    user: settings.user,
    host: settings.hostname,
    port: '22',
    file: jsesc(settings.sourcepath + filepath, {
      'quotes': 'double',
      'wrap': true
    }),
    path: jsesc(settings.destinationpath + filepath, {
      'quotes': 'double',
      'wrap': true
    })
  }

  if (options.path.indexOf(' ') >= 0) {
    log('[abort] whitespaces not allowed');
    return;
  } else {
    // log(options);
    //log('[note] transfer to: ', settings.destinationpath + filepath);
    log('[note] transfer to: ', options.path);

    scp.send(options, function (err) {
      if (err) log('Transfer error: ' + err);
      else log('[ok] transferred: ' + options.path);
    });
  }

};

ScpSync.prototype.remove = function(filepath) {
  var self = this;
  log('remove: ', filepath);

  var removepath = jsesc(settings.destinationpath + filepath, {
    'quotes': 'double',
    'wrap': true
  });
  var cmd = 'rm -r ' + removepath;
  log('remove cmd: ', cmd);

  var rm = exec(cmd, {
    user: settings.user,
    host: settings.remoteip
  }).pipe(process.stdout)

  rm.on('end', function() {
    log('rm end');
  });
  rm.on('error', function(err) {
    log('rm err: ', err);
  });
};

/*****************************************
 * test with filename containing space
 */
// setTimeout(function() {
//   fs.writeFile(sourcepath + 'test folder.txt', '', function(err) {
//     if (err) console.log(err);
//     console.log('created file');
//   });
// }, 5000);
//
// setTimeout(function() {
//   console.log('unlink file...');
//   fs.unlink(sourcepath + 'test folder.txt')
// }, 15000);

/*****************************************
 * watcher events
 * 'add', 'addDir' and 'change' events also receive stat() results as second
 * argument when available: http://nodejs.org/api/fs.html#fs_class_fs_stats
 */
// watcher.on('change', function(path, stats) {
//   if (stats) console.log('File', path, 'changed size to', stats.size);
// });

// // Watch new files.
// watcher.add('new-file');
// watcher.add(['new-file-2', 'new-file-3', '**/other-file*']);
//
// // Un-watch some files.
// watcher.unwatch('new-file*');
//
// // Only needed if watching is `persistent: true`.
// watcher.close();

// // Full list of options. See below for descriptions.
// chokidar.watch('file', {
//   persistent: true,
//
//   ignored: '*.txt',
//   ignoreInitial: false,
//   followSymlinks: true,
//   cwd: '.',
//
//   usePolling: true,
//   alwaysStat: false,
//   depth: undefined,
//   interval: 100,
//
//   ignorePermissionErrors: false,
//   atomic: true
// });
<commit_msg>use cad if no source path specified<commit_after>'use strict';

/*****************************************
 * setup
 */

/*****************************************
 * copy ssh key
 * cat ~/.ssh/id_rsa.pub | ssh wifibox 'cat >> /etc/dropbear/authorized_keys'
 *
 * make global executable node npm package
 * http://www.anupshinde.com/posts/how-to-create-nodejs-npm-package/
 */

//--requires
var chokidar = require('chokidar');
var scp = require('scp');
var exec = require('ssh-exec');
var fs = require('fs');
var jsesc = require('jsesc');
var program = program = require('commander');
//var config = require('config');

//--export
module.exports = ScpSync;

//--console
var log = console.log.bind(console);

//--vars
var settings = {
  sourcepath: undefined,
  destinationpath: undefined,
  user: undefined,
  remoteip: undefined,
  hostname: undefined
}

/*****************************************
 * main
 */
function ScpSync() {
  if (!(this instanceof ScpSync)) return new ScpSync();

  var self = this;

  //--init cli
  this.init(function() {
    //--initial transfer of files from source to remote dir
    self.transfer('.');

    //--setup watcher
    self.watcher = chokidar.watch('.', {
      ignored: /[\/\\]\./,
      persistent: true,
      cwd: settings.sourcepath,
      ignoreInitial: true
    });

    //--watcher events
    self.watcher
      .on('change', self.transfer)
      .on('add', self.transfer)
      .on('unlink', self.remove)
      // More events.
      .on('addDir', self.transfer)
      .on('unlinkDir', self.remove)
      .on('error', function(error) {
        log('error: ', error);
      })
      .on('ready', function() {
        log('Initial scan complete. Ready for changes...');
      })
      .on('raw', function(event, path, details) {
        //log('Raw event info:', event, path, details);
      });
  });
}

/*****************************************
 * functions
 */
ScpSync.prototype.init = function(cb) {
  var self = this;

  //--program setup
  program
    .version('1.0.0')
    .usage('[options] [dir]')
    .option('-s, --sourcepath <sourcepath>', 'specify source folder')
    .option('-d, --destination <destination>', 'specify destination folder')
    .option('-u, --user <user>', 'specifiy remote user name')
    .option('-i, --remoteip <remoteip>', 'specifiy host ip x.x.x.x')
    .option('-n, --hostname <hostname>', 'specifiy ssh hostname')
    .parse(process.argv);

  //--source
  if (program.sourcepath === undefined || program.sourcepath === '.') {
    settings.sourcepath = process.cwd() + '/';
    console.error("source (cwd):", settings.sourcepath);
    // return 1;
  } else {
    settings.sourcepath = program.sourcepath;
    log('source:', settings.sourcepath);
  }

  //--destination
  if (program.destination) {
    settings.destinationpath = program.destination;
    log('destination:', settings.destinationpath);
  } else {
    console.error("no destination specified");
    return 1;
  }

  //--user
  if (program.user) {
    settings.user = program.user;
    log('user:', settings.user);
  } else {
    console.error("no user specified");
    return 1;
  }

  //--hostip
  if (program.remoteip) {
    settings.remoteip = program.remoteip;
    log('remoteip:', settings.remoteip);
  } else {
    console.error("no remoteip specified");
    return 1;
  }

  //--hostname
  if (program.hostname) {
    settings.hostname = program.hostname;
    log('hostname:', settings.hostname);
  } else {
    console.error("no hostname specified");
    return 1;
  }

  //--make sure destination path exists
  var cmd = 'mkdir -p ' + settings.destinationpath;
  log('[note] mkdir cmd: ', cmd);

  var mkdir = exec(cmd, {
    user: settings.user,
    host: settings.remoteip,
  }).pipe(process.stdout);

  //--wait some seconds for mkdir -p to have completed
  setTimeout(function() {
    return cb();
  }, 3000);
};

ScpSync.prototype.transfer = function(filepath) {
  var self = this;
  log('[note] transfer from: ', settings.sourcepath + filepath);

  if (filepath === '') {
    filepath = '.';
  }

  var options = {
    user: settings.user,
    host: settings.hostname,
    port: '22',
    file: jsesc(settings.sourcepath + filepath, {
      'quotes': 'double',
      'wrap': true
    }),
    path: jsesc(settings.destinationpath + filepath, {
      'quotes': 'double',
      'wrap': true
    })
  }

  if (options.path.indexOf(' ') >= 0) {
    log('[abort] whitespaces not allowed');
    return;
  } else {
    // log(options);
    //log('[note] transfer to: ', settings.destinationpath + filepath);
    log('[note] transfer to: ', options.path);

    scp.send(options, function (err) {
      if (err) log('Transfer error: ' + err);
      else log('[ok] transferred: ' + options.path);
    });
  }

};

ScpSync.prototype.remove = function(filepath) {
  var self = this;
  log('remove: ', filepath);

  var removepath = jsesc(settings.destinationpath + filepath, {
    'quotes': 'double',
    'wrap': true
  });
  var cmd = 'rm -r ' + removepath;
  log('remove cmd: ', cmd);

  var rm = exec(cmd, {
    user: settings.user,
    host: settings.remoteip
  }).pipe(process.stdout)

  rm.on('end', function() {
    log('rm end');
  });
  rm.on('error', function(err) {
    log('rm err: ', err);
  });
};

/*****************************************
 * test with filename containing space
 */
// setTimeout(function() {
//   fs.writeFile(sourcepath + 'test folder.txt', '', function(err) {
//     if (err) console.log(err);
//     console.log('created file');
//   });
// }, 5000);
//
// setTimeout(function() {
//   console.log('unlink file...');
//   fs.unlink(sourcepath + 'test folder.txt')
// }, 15000);

/*****************************************
 * watcher events
 * 'add', 'addDir' and 'change' events also receive stat() results as second
 * argument when available: http://nodejs.org/api/fs.html#fs_class_fs_stats
 */
// watcher.on('change', function(path, stats) {
//   if (stats) console.log('File', path, 'changed size to', stats.size);
// });

// // Watch new files.
// watcher.add('new-file');
// watcher.add(['new-file-2', 'new-file-3', '**/other-file*']);
//
// // Un-watch some files.
// watcher.unwatch('new-file*');
//
// // Only needed if watching is `persistent: true`.
// watcher.close();

// // Full list of options. See below for descriptions.
// chokidar.watch('file', {
//   persistent: true,
//
//   ignored: '*.txt',
//   ignoreInitial: false,
//   followSymlinks: true,
//   cwd: '.',
//
//   usePolling: true,
//   alwaysStat: false,
//   depth: undefined,
//   interval: 100,
//
//   ignorePermissionErrors: false,
//   atomic: true
// });
<|endoftext|>


<commit_before>'use strict';

function KewScan(CardovaService) {

  CordovaService.ready.then(function() {
    this.scanner = cordova.require("cordova/plugin/BarcodeScanner");

    this.scan = function() {
      return this.scanner.scan(function(result) {
        if (result.cancelled) {
          return {};
        }

        if (!result.text) {
          return { error: 'Can not read code' };
        }

        if(result.format != "QR_CODE") {
          return { error: "Unknown barcode format" };
        }

        return { code: result.text };

      }, function(error) {
        return { error: "Scanning failed: " + error};
      })
    }

  });

}

/*
return {
  scan: function() {

    CordovaService.ready.then(function() {

      var scanner = cordova.require("cordova/plugin/BarcodeScanner");

      scanner.scan( function (result) {

         console.log("Scanner result: \n" +
              "text: " + result.text + "\n" +
              "format: " + result.format + "\n" +
              "cancelled: " + result.cancelled + "\n");

          // if result.cancelled {
          //     return;
          // }

          // if (!result.text) {
          //     response.error = "Can not read barcode";
          //     return;
          // }

          // if (args.format != "QR_CODE") {
          //     response.error = "Unknown barcode format";
          //     return;
          // }

      }, function (error) {
          console.log("Scanning failed: ", error);
      } );

    });
  }
}
*/

angular.module('myApp.scannerService', ['fsCordova'])
    .factory('Scanner', ['CordovaService',
        function (CordovaService) {
          return new KewScan(CardovaService);
        }]);<commit_msg>Tidyup scan service<commit_after>'use strict';

angular.module('myApp.scannerService', ['fsCordova'])
    .factory('Scanner', ['CordovaService',
        function (CordovaService) {
          return {
            scan: function() {

              return CordovaService.ready.then(function() {

                var scanner = cordova.require("cordova/plugin/BarcodeScanner");

                scanner.scan( function (result) {

                   console.log("Scanner result: \n" +
                        "text: " + result.text + "\n" +
                        "format: " + result.format + "\n" +
                        "cancelled: " + result.cancelled + "\n");

                    if (result.cancelled) {
                        return {};
                    }

                    if (!result.text) {
                        return { error: "Can not read barcode"};
                    }

                    if (result.format != "QR_CODE") {
                        return { error: "Unknown barcode format" };
                    }

                    return { code: result.text };

                }, function (error) {
                  return { error: "Scanning failed: " + error };
                } );

              });
            }
          }
        }]);<|endoftext|>


<commit_before>var Schema = require('./schema');
var _ = require('lodash');

module.exports = function(ns, docs) {
  if (!Array.isArray(docs)) {
    docs = [docs];
  }
  var schema = new Schema({
    ns: ns
  });
  _.each(docs, function(doc) {
    schema.sample(doc);
  });
  return schema;
};

module.exports.extend = Schema.extend.bind(Schema);
module.exports.Schema = Schema;
module.exports.getType = require('./type').getNameFromValue;
module.exports.FieldCollection = Schema.FieldCollection;
module.exports.BasicField = Schema.BasicField;
module.exports.EmbeddedArrayField = Schema.EmbeddedArrayField;
module.exports.EmbeddedDocumentField = Schema.EmbeddedDocumentField;
<commit_msg>make module.exports use streams + optional callback<commit_after>var Schema = require('./schema');
var es = require('event-stream');

module.exports = function(ns, docs, fn) {
  if (!Array.isArray(docs)) {
    docs = [docs];
  }
  var schema = new Schema({
    ns: ns
  });

  var stream = es.readArray(docs).pipe(schema.stream());
  if (fn) {
    stream.on('end', fn);
  }

  return schema;
};

module.exports.extend = Schema.extend.bind(Schema);
module.exports.Schema = Schema;
module.exports.getType = require('./type').getNameFromValue;
module.exports.FieldCollection = Schema.FieldCollection;
module.exports.BasicField = Schema.BasicField;
module.exports.EmbeddedArrayField = Schema.EmbeddedArrayField;
module.exports.EmbeddedDocumentField = Schema.EmbeddedDocumentField;
<|endoftext|>


<commit_before>//the object
var engine = global.engine = {};

engine.VERSION = require('../../../package.json').version;

engine.init = function (options, callback) {
  callback = callback || emptyfunc;
  //common
  engine.common = require('./common/index');
  engine.config = require('./common/config');
  engine.logger = require('./common/logger');
  engine.db = require('./common/db');
  engine.events = require('./common/events');

  //services
  engine.bitcoin = require('./services/bitcoin');
  engine.pockets = require('./services/pockets');

  engine.options = engine.common.extend({
    //default options
    promisify: false
  }, options || {});
  if (engine.options.promisify)
    engine.promisify();
  engine.logger.info('Starting Pockets Library, version [' + engine.VERSION + '].');
  engine.logger.debug('Options: ' + JSON.stringify(engine.options));
  engine.pockets.load({}, function (err) {
    if (err)
      return callback(err);
    return callback(null);
  });
};

engine.promisify = function () {
  var promisify = require('thenify-all');
  engine.bitcoin = promisify.withCallback(engine.bitcoin);
  engine.pockets = promisify.withCallback(engine.pockets);
};

//inject globals
require('./common/globals');

//fire the engine up if we're running in a browser
if (typeof global.localStorage !== 'undefined')
  engine.init({promisify: true});<commit_msg>#1 additional jsdocs.<commit_after>/**
 * The main entry point for Pockets
 */

//Stores reference (including global) to the engine\
var engine = global.engine = {};

engine.VERSION = require('../../../package.json').version;

/**
 * Initialize the engine
 * @param {object} options holds the different options available for the engine
 * @param {function} callback the callback function to call when done.
 */
engine.init = function (options, callback) {
  callback = callback || emptyfunc;
  //common
  engine.common = require('./common/index');
  engine.config = require('./common/config');
  engine.logger = require('./common/logger');
  engine.db = require('./common/db');
  engine.events = require('./common/events');

  //services
  engine.bitcoin = require('./services/bitcoin');
  engine.pockets = require('./services/pockets');

  engine.options = engine.common.extend({
    //default options
    promisify: false
  }, options || {});
  if (engine.options.promisify)
    engine.promisify();
  engine.logger.info('Starting Pockets Library, version [' + engine.VERSION + '].');
  engine.logger.debug('Options: ' + JSON.stringify(engine.options));
  engine.pockets.load({}, function (err) {
    if (err)
      return callback(err);
    return callback(null);
  });
};

/**
 * Promisify the engine's services to be consumed by AngularJS and alike.
 */
engine.promisify = function () {
  var promisify = require('thenify-all');
  engine.bitcoin = promisify.withCallback(engine.bitcoin);
  engine.pockets = promisify.withCallback(engine.pockets);
};

/**
 * We globally inject global vars
 */
//inject globals
require('./common/globals');

/**
 * When a browser is detected the engine will init itself automatically.
 */
//fire the engine up if we're running in a browser
if (typeof global.localStorage !== 'undefined')
  engine.init({promisify: true});<|endoftext|>


<commit_before>'use strict'

const packageJson = require('./package.json')
const version = packageJson.version

// Gulp utility
const gulp = require('gulp')
const del = require('del')
const rename = require('gulp-rename')
const runSequence = require('run-sequence')

// Templates
const transpiler = require('./lib/transpilation/transpiler.js')

// Styles
const sass = require('gulp-sass')
const sasslint = require('gulp-sass-lint')
const nano = require('gulp-cssnano')

// Javascript
const standard = require('gulp-standard')
const rollup = require('rollup-stream')
const vinylSource = require('vinyl-source-stream')
const vinylBuffer = require('vinyl-buffer')
const uglify = require('gulp-uglify')
const uglifySaveLicense = require('uglify-save-license')

// Testing
const mocha = require('gulp-mocha')
const jasmineBrowser = require('gulp-jasmine-browser')
const SpecReporter = require('jasmine-spec-reporter')

// Packaging
const tar = require('gulp-tar')
const gzip = require('gulp-gzip')

// Configuration
const paths = require('./config/paths.js')

// Task for cleaning the distribution
gulp.task('clean', () => {
  return del([paths.dist + '*'])
})

// Task for transpiling the templates
let transpileRunner = templateLanguage => {
  return gulp.src(paths.templates + '*.html')
    .pipe(transpiler(templateLanguage, version))
    .pipe(rename({extname: '.html.' + templateLanguage}))
    .pipe(gulp.dest(paths.distTemplates))
}
gulp.task('build:templates', ['build:templates:nunjucks', 'build:templates:erb', 'build:templates:handlebars', 'build:templates:django'])
gulp.task('build:templates:nunjucks', transpileRunner.bind(null, 'nunjucks'))
gulp.task('build:templates:erb', transpileRunner.bind(null, 'erb'))
gulp.task('build:templates:handlebars', transpileRunner.bind(null, 'handlebars'))
gulp.task('build:templates:django', transpileRunner.bind(null, 'django'))

// Compile Sass to CSS
gulp.task('build:styles', cb => {
  runSequence('lint:styles', ['build:styles:copy', 'build:styles:compile'], cb)
})
gulp.task('build:styles:compile', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(paths.distCSS))
    .pipe(rename({ suffix: '.min' }))
    .pipe(nano())
    .pipe(gulp.dest(paths.distCSS))
})
gulp.task('build:styles:copy', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(gulp.dest(paths.distScss))
})

// Build single Javascript file from modules
let scriptsBuilder = fileName => {
  return rollup({
    entry: paths.assetsJs + fileName + '.manifest.js',
    context: 'window'
  })
    .pipe(vinylSource(fileName + '.js'))
    .pipe(gulp.dest(paths.distJs))
    .pipe(vinylBuffer())
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify({
      preserveComments: uglifySaveLicense
    }))
    .pipe(gulp.dest(paths.distJs))
}
gulp.task('build:scripts', cb => {
  runSequence('lint:scripts', [
    'build:scripts:copy',
    'build:scripts:elements',
    'build:scripts:govuk-template',
    'build:scripts:govuk-template-ie',
    'build:scripts:toolkit'
  ], cb)
})
gulp.task('build:scripts:elements', scriptsBuilder.bind(null, 'elements'))
gulp.task('build:scripts:govuk-template', scriptsBuilder.bind(null, 'govuk-template'))
gulp.task('build:scripts:govuk-template-ie', scriptsBuilder.bind(null, 'govuk-template-ie'))
gulp.task('build:scripts:toolkit', scriptsBuilder.bind(null, 'toolkit'))
gulp.task('build:scripts:copy', () => {
  gulp.src(paths.assetsJs + '**/*.js')
    .pipe(gulp.dest(paths.distJs))
})

// Task to run the tests
gulp.task('test', ['test:lib', 'test:toolkit'])
gulp.task('test:lib', () => gulp.src(paths.testSpecs + '*.js', {read: false})
  .pipe(mocha())
)
// Ideally these pre-existing toolkit tests will be rewritten at some point
// to use mocha rather than requiring Jasmine as well.
gulp.task('test:toolkit', () => gulp.src([
  paths.npm + 'jquery/dist/jquery.js',
  paths.assetsJs + 'toolkit/**/*.js',
  paths.testSpecs + 'toolkit/unit/**/*.spec.js'
])
  .pipe(jasmineBrowser.specRunner({console: true}))
  .pipe(jasmineBrowser.headless({reporter: new SpecReporter()}))
)

// Linting
gulp.task('lint', ['lint:styles', 'lint:scripts', 'lint:tests'])
gulp.task('lint:styles', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(sasslint({
      config: paths.config + '.sass-lint.yml'
    }))
    .pipe(sasslint.format())
    .pipe(sasslint.failOnError())
})
gulp.task('lint:scripts', () => {
  gulp.src([
    '!' + paths.assetsJs + '**/vendor/**/*.js',
    paths.assetsJs + '**/*.js'
  ])
    .pipe(standard())
    .pipe(standard.reporter('default', {
      breakOnError: true,
      quiet: true
    }))
})
gulp.task('lint:tests', () => {
  gulp.src(paths.test + '**/*.js')
    .pipe(standard())
    .pipe(standard.reporter('default', {
      breakOnError: true,
      quiet: true
    }))
})

// Build distribution
gulp.task('build', cb => {
  runSequence('clean', ['build:templates', 'build:styles', 'build:scripts'], cb)
})

// Packaging
gulp.task('package', () => gulp.src('src/*')
  .pipe(tar('dist/*'))
  .pipe(gzip())
  .pipe(gulp.dest('dist/pkg/*'))
)

<commit_msg>Amend package task<commit_after>'use strict'

const packageJson = require('./package.json')
const version = packageJson.version

// Gulp utility
const gulp = require('gulp')
const del = require('del')
const rename = require('gulp-rename')
const runSequence = require('run-sequence')

// Templates
const transpiler = require('./lib/transpilation/transpiler.js')

// Styles
const sass = require('gulp-sass')
const sasslint = require('gulp-sass-lint')
const nano = require('gulp-cssnano')

// Javascript
const standard = require('gulp-standard')
const rollup = require('rollup-stream')
const vinylSource = require('vinyl-source-stream')
const vinylBuffer = require('vinyl-buffer')
const uglify = require('gulp-uglify')
const uglifySaveLicense = require('uglify-save-license')

// Testing
const mocha = require('gulp-mocha')
const jasmineBrowser = require('gulp-jasmine-browser')
const SpecReporter = require('jasmine-spec-reporter')

// Packaging
const tar = require('gulp-tar')
const gzip = require('gulp-gzip')

// Configuration
const paths = require('./config/paths.js')

// Task for cleaning the distribution
gulp.task('clean', () => {
  return del([paths.dist + '*'])
})

// Task for transpiling the templates
let transpileRunner = templateLanguage => {
  return gulp.src(paths.templates + '*.html')
    .pipe(transpiler(templateLanguage, version))
    .pipe(rename({extname: '.html.' + templateLanguage}))
    .pipe(gulp.dest(paths.distTemplates))
}
gulp.task('build:templates', ['build:templates:nunjucks', 'build:templates:erb', 'build:templates:handlebars', 'build:templates:django'])
gulp.task('build:templates:nunjucks', transpileRunner.bind(null, 'nunjucks'))
gulp.task('build:templates:erb', transpileRunner.bind(null, 'erb'))
gulp.task('build:templates:handlebars', transpileRunner.bind(null, 'handlebars'))
gulp.task('build:templates:django', transpileRunner.bind(null, 'django'))

// Compile Sass to CSS
gulp.task('build:styles', cb => {
  runSequence('lint:styles', ['build:styles:copy', 'build:styles:compile'], cb)
})
gulp.task('build:styles:compile', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(paths.distCSS))
    .pipe(rename({ suffix: '.min' }))
    .pipe(nano())
    .pipe(gulp.dest(paths.distCSS))
})
gulp.task('build:styles:copy', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(gulp.dest(paths.distScss))
})

// Build single Javascript file from modules
let scriptsBuilder = fileName => {
  return rollup({
    entry: paths.assetsJs + fileName + '.manifest.js',
    context: 'window'
  })
    .pipe(vinylSource(fileName + '.js'))
    .pipe(gulp.dest(paths.distJs))
    .pipe(vinylBuffer())
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify({
      preserveComments: uglifySaveLicense
    }))
    .pipe(gulp.dest(paths.distJs))
}
gulp.task('build:scripts', cb => {
  runSequence('lint:scripts', [
    'build:scripts:copy',
    'build:scripts:elements',
    'build:scripts:govuk-template',
    'build:scripts:govuk-template-ie',
    'build:scripts:toolkit'
  ], cb)
})
gulp.task('build:scripts:elements', scriptsBuilder.bind(null, 'elements'))
gulp.task('build:scripts:govuk-template', scriptsBuilder.bind(null, 'govuk-template'))
gulp.task('build:scripts:govuk-template-ie', scriptsBuilder.bind(null, 'govuk-template-ie'))
gulp.task('build:scripts:toolkit', scriptsBuilder.bind(null, 'toolkit'))
gulp.task('build:scripts:copy', () => {
  gulp.src(paths.assetsJs + '**/*.js')
    .pipe(gulp.dest(paths.distJs))
})

// Task to run the tests
gulp.task('test', ['test:lib', 'test:toolkit'])
gulp.task('test:lib', () => gulp.src(paths.testSpecs + '*.js', {read: false})
  .pipe(mocha())
)
// Ideally these pre-existing toolkit tests will be rewritten at some point
// to use mocha rather than requiring Jasmine as well.
gulp.task('test:toolkit', () => gulp.src([
  paths.npm + 'jquery/dist/jquery.js',
  paths.assetsJs + 'toolkit/**/*.js',
  paths.testSpecs + 'toolkit/unit/**/*.spec.js'
])
  .pipe(jasmineBrowser.specRunner({console: true}))
  .pipe(jasmineBrowser.headless({reporter: new SpecReporter()}))
)

// Linting
gulp.task('lint', ['lint:styles', 'lint:scripts', 'lint:tests'])
gulp.task('lint:styles', () => {
  gulp.src(paths.assetsScss + '**/*.scss')
    .pipe(sasslint({
      config: paths.config + '.sass-lint.yml'
    }))
    .pipe(sasslint.format())
    .pipe(sasslint.failOnError())
})
gulp.task('lint:scripts', () => {
  gulp.src([
    '!' + paths.assetsJs + '**/vendor/**/*.js',
    paths.assetsJs + '**/*.js'
  ])
    .pipe(standard())
    .pipe(standard.reporter('default', {
      breakOnError: true,
      quiet: true
    }))
})
gulp.task('lint:tests', () => {
  gulp.src(paths.test + '**/*.js')
    .pipe(standard())
    .pipe(standard.reporter('default', {
      breakOnError: true,
      quiet: true
    }))
})

// Build distribution
gulp.task('build', cb => {
  runSequence('clean', ['build:templates', 'build:styles', 'build:scripts'], cb)
})

// Packaging
gulp.task('package', () =>
  gulp.src(paths.dist + '*')
    .pipe(tar(packageName + '.tar'))
    .pipe(gzip())
    .pipe(gulp.dest(paths.dist))
)

<|endoftext|>


<commit_before>/* @flow */

import { Disposable } from 'atom'
import Linter from './main'
import type { State, UI, Linter as LinterProvider } from './types'

export default {
  state: null,
  instance: null,

  activate(state: State) {
    if (!atom.inSpecMode()) {
      // eslint-disable-next-line
      require('atom-package-deps').install('linter', true)
    }
    this.instance = new Linter(state)
  },
  serialize(): State {
    return this.state
  },
  consumeLinter(linter: Linter): Disposable {
    const linters = [].concat(linter)
    for (const entry of linters) {
      this.instance.addLinter(entry)
    }
    return new Disposable(() => {
      for (const entry of linters) {
        this.instance.deleteLinter(entry)
      }
    })
  },
  consumeLinterLegacy(linter: LinterProvider): Disposable {
    const linters = [].concat(linter)
    for (const entry of linters) {
      linter.name = linter.name || 'Unknown'
      linter.lintOnFly = Boolean(linter.lintOnFly)
      this.instance.addLinter(entry, true)
    }
    return new Disposable(() => {
      for (const entry of linters) {
        this.instance.deleteLinter(entry)
      }
    })
  },
  consumeUI(ui: UI): Disposable {
    const uis = [].concat(ui)
    for (const entry of uis) {
      this.instance.addUI(entry)
    }
    return new Disposable(() => {
      for (const entry of uis) {
        this.instance.deleteUI(entry)
      }
    })
  },
  provideIndie(): Object {
    return indie =>
      this.instance.registryIndie.register(indie)
  },
  deactivate() {
    this.instance.dispose()
  },
}
<commit_msg>:art: Address reviewer's comments<commit_after>/* @flow */

import { Disposable } from 'atom'
import Linter from './main'
import type { State, UI, Linter as LinterProvider } from './types'

export default {
  state: null,
  instance: null,

  activate(state: State) {
    if (!atom.inSpecMode()) {
      // eslint-disable-next-line global-require
      require('atom-package-deps').install('linter', true)
    }
    this.instance = new Linter(state)
  },
  serialize(): State {
    return this.state
  },
  consumeLinter(linter: Linter): Disposable {
    const linters = [].concat(linter)
    for (const entry of linters) {
      this.instance.addLinter(entry)
    }
    return new Disposable(() => {
      for (const entry of linters) {
        this.instance.deleteLinter(entry)
      }
    })
  },
  consumeLinterLegacy(linter: LinterProvider): Disposable {
    const linters = [].concat(linter)
    for (const entry of linters) {
      linter.name = linter.name || 'Unknown'
      linter.lintOnFly = Boolean(linter.lintOnFly)
      this.instance.addLinter(entry, true)
    }
    return new Disposable(() => {
      for (const entry of linters) {
        this.instance.deleteLinter(entry)
      }
    })
  },
  consumeUI(ui: UI): Disposable {
    const uis = [].concat(ui)
    for (const entry of uis) {
      this.instance.addUI(entry)
    }
    return new Disposable(() => {
      for (const entry of uis) {
        this.instance.deleteUI(entry)
      }
    })
  },
  provideIndie(): Object {
    return indie =>
      this.instance.registryIndie.register(indie)
  },
  deactivate() {
    this.instance.dispose()
  },
}
<|endoftext|>


<commit_before>import { documentHelpers, Command } from 'substance'
import { findParentByType } from './nodeHelpers'
import CustomMetadataField from '../models/CustomMetadataField'

class BasicCustomMetadataFieldCommand extends Command {
  getCommandState (params, context) {
    return {
      disabled: this.isDisabled(params, context)
    }
  }

  isDisabled (params) {
    const xpath = params.selectionState.xpath
    return !xpath.find(n => n.type === 'custom-metadata-field')
  }
}

export class AddCustomMetadataFieldCommand extends BasicCustomMetadataFieldCommand {
  execute (params, context) {
    let collectionPath = this._getCollectionPath(params, context)
    context.editorSession.transaction(tx => {
      let node = documentHelpers.createNodeFromJson(tx, CustomMetadataField.getTemplate())
      documentHelpers.append(tx, collectionPath, node.id)
      tx.setSelection({
        type: 'property',
        path: [node.id, 'value'],
        startOffset: 0
      })
    })
  }

  _getCollectionPath (params, context) {
    const doc = params.editorSession.getDocument()
    const nodeId = params.selection.getNodeId()
    const node = doc.get(nodeId)
    let figurePanelId = node.id
    if (node.type !== 'figure-panel') {
      const parentFigurePanel = findParentByType(node, 'figure-panel')
      figurePanelId = parentFigurePanel.id
    }
    return [figurePanelId, 'metadata']
  }
}
<commit_msg>Move and remove commands for custom fields.<commit_after>import { documentHelpers, Command } from 'substance'
import { findParentByType } from './nodeHelpers'
import CustomMetadataField from '../models/CustomMetadataField'

class BasicCustomMetadataFieldCommand extends Command {
  get contextType () {
    return 'custom-metadata-field'
  }

  getCommandState (params, context) {
    return {
      disabled: this.isDisabled(params, context)
    }
  }

  isDisabled (params) {
    const xpath = params.selectionState.xpath
    return !xpath.find(n => n.type === this.contextType)
  }

  _getCollectionPath (params, context) {
    const doc = params.editorSession.getDocument()
    const nodeId = params.selection.getNodeId()
    const node = doc.get(nodeId)
    let figurePanelId = node.id
    if (node.type !== 'figure-panel') {
      const parentFigurePanel = findParentByType(node, 'figure-panel')
      figurePanelId = parentFigurePanel.id
    }
    return [figurePanelId, 'metadata']
  }
}

export class AddCustomMetadataFieldCommand extends BasicCustomMetadataFieldCommand {
  get contextType () {
    return 'figure-panel'
  }

  execute (params, context) {
    const collectionPath = this._getCollectionPath(params, context)
    context.editorSession.transaction(tx => {
      let node = documentHelpers.createNodeFromJson(tx, CustomMetadataField.getTemplate())
      documentHelpers.append(tx, collectionPath, node.id)
      // TODO: we need to pass surfaceId here
      tx.setSelection({
        type: 'property',
        path: [node.id, 'value'],
        startOffset: 0
      })
    })
  }
}

export class RemoveCustomMetadataFieldCommand extends BasicCustomMetadataFieldCommand {
  execute (params, context) {
    const collectionPath = this._getCollectionPath(params, context)
    context.editorSession.transaction(tx => {
      const nodeId = tx.selection.getNodeId()
      documentHelpers.append(tx, collectionPath, nodeId)
      tx.selection = null
    })
  }
}

export class MoveCustomMetadataFieldCommand extends BasicCustomMetadataFieldCommand {
  execute (params, context) {
    const direction = this.config.direction
    const collectionPath = this._getCollectionPath(params, context)
    const nodeId = params.selection.getNodeId()
    const doc = context.editorSession.getDocument()
    const customField = doc.get(nodeId)
    const shift = direction === 'up' ? -1 : 1
    context.api._moveChild(collectionPath, customField, shift)
  }

  isDisabled (params, context) {
    const matchSelection = !super.isDisabled(params)
    if (matchSelection) {
      const direction = this.config.direction
      const collectionPath = this._getCollectionPath(params, context)
      const nodeId = params.selection.getNodeId()
      const doc = context.editorSession.getDocument()
      const customFieldsIndex = doc.get(collectionPath)
      const currentIndex = customFieldsIndex.indexOf(nodeId)
      if (customFieldsIndex.length > 0) {
        if ((direction === 'up' && currentIndex > 0) || (direction === 'down' && currentIndex < customFieldsIndex.length - 1)) {
          return false
        }
      }
    }
    return true
  }
}
<|endoftext|>


<commit_before>"use strict";

var util  = require("util");
var OAuth = require("passport-oauth").OAuth2Strategy;

function AzureOAuth2 (options, verify) {
  options = options || {};

  var base   = options.base   || "https://login.windows.net/";
  var tenant = options.tenant || "common";

  var authorizationURL = base + tenant + "/oauth2/authorize";
  var tokenURL         = base + tenant + "/oauth2/token";

  options.authorizationURL = options.authorizationURL || authorizationURL;
  options.tokenURL = options.tokenURL || tokenURL;

  OAuth.call(this, options, verify);

  this.name = "azure_oauth2";
  this.resource = options.resource;
  this.prompt = options.prompt;
  this.state = options.state;
}

util.inherits(AzureOAuth2, OAuth);

AzureOAuth2.prototype.authenticate = function (req, options) {
  if (!options.resource && this.resource) {
    options.resource = this.resource;
  }

  if (!options.prompt && this.prompt) {
    options.prompt = this.prompt;
  }

  OAuth.prototype.authenticate.call(this, req, options);
};

AzureOAuth2.prototype.userProfile = function (accessToken, done) {
  done(null, { provider: "azure_oauth2" });
};

AzureOAuth2.prototype.authorizationParams = function (options) {
  return options;
};

module.exports = AzureOAuth2;
<commit_msg>first commit<commit_after>"use strict";

var util  = require("util");
var OAuth = require("passport-oauth").OAuth2Strategy;

function AzureOAuth2 (options, verify) {
  options = options || {};

  var base   = options.base   || "https://login.windows.net/";
  var tenant = options.tenant || "common";

  var authorizationURL = base + tenant + "/oauth2/authorize";
  var tokenURL         = base + tenant + "/oauth2/token";

  options.authorizationURL = options.authorizationURL || authorizationURL;
  options.tokenURL = options.tokenURL || tokenURL;

  OAuth.call(this, options, verify);

  this.name = "azure_oauth2";
  this.resource = options.resource;
  this.prompt = options.prompt;
  this.state = options.state;
}

util.inherits(AzureOAuth2, OAuth);

AzureOAuth2.prototype.authenticate = function (req, options) {
  if (!options.resource && this.resource) {
    options.resource = this.resource;
  }

  if (!options.prompt && this.prompt) {
    options.prompt = this.prompt;
  }

  OAuth.prototype.authenticate.call(this, req, options);
};

AzureOAuth2.prototype.authorizationParams = function (options) {
  return options;
};

AzureOAuth2.prototype.userProfile = function (accessToken, done) {
  done(null, { provider: "azure_oauth2" });
};

module.exports = AzureOAuth2;
<|endoftext|>


<commit_before>import { Platform, AppRegistry, DeviceEventEmitter, NativeEventEmitter, NativeModules } from 'react-native';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';

const { TrackPlayerModule: TrackPlayer } = NativeModules;
const emitter = Platform.OS !== 'android' ? new NativeEventEmitter(TrackPlayer) : DeviceEventEmitter;

function resolveAsset(uri) {
    if(!uri) return undefined;
    return resolveAssetSource(uri);
}

function resolveUrl(url) {
    if(!url) return undefined;
    return resolveAssetSource(url) || url;
}

function setupPlayer(options) {
    return TrackPlayer.setupPlayer(options || {});
}

function updateOptions(data) {
    // Clone the object before modifying it, so we don't run into problems with immutable objects
    data = Object.assign({}, data);

    // Resolve the asset for each icon
    data.icon = resolveAsset(data.icon);
    data.playIcon = resolveAsset(data.playIcon);
    data.pauseIcon = resolveAsset(data.pauseIcon);
    data.stopIcon = resolveAsset(data.stopIcon);
    data.previousIcon = resolveAsset(data.previousIcon);
    data.nextIcon = resolveAsset(data.nextIcon);

    return TrackPlayer.updateOptions(data);
}

function add(tracks, insertBeforeId) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    for(let i = 0; i < tracks.length; i++) {
        // Clone the object before modifying it
        tracks[i] = Object.assign({}, tracks[i]);

        // Resolve the URLs
        tracks[i].url = resolveUrl(tracks[i].url);
        tracks[i].artwork = resolveUrl(tracks[i].artwork);

        // Cast ID's into strings
        tracks[i].id = `${tracks[i].id}`
    }

    return TrackPlayer.add(tracks, insertBeforeId);
}

function remove(tracks) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    return TrackPlayer.remove(tracks);
}

function registerBackendService(serviceFactory) {
    if (Platform.OS === 'android') {
        // Registers the headless task
        AppRegistry.registerHeadlessTask('TrackPlayer', serviceFactory);
    } else {
        // Initializes and runs the service in the next tick
        setImmediate(serviceFactory());
    }
}

function addEventListener(event, listener) {
    return emitter.addListener(event, listener);
}

function warpEventResponse(handler, event, payload) {
    // transform into the old format and return to handler
    const additionalKeys = payload || {};
    handler({ type: event, ...additionalKeys });
}

/**
 * @deprecated since version 1.0.1. Use addEventListener instead.
 */
function registerEventHandler(handler) {
    let events = [
        'playback-state',
        'playback-error',
        'playback-queue-ended',
        'playback-track-changed',

        'remote-play',
        'remote-pause',
        'remote-stop',
        'remote-next',
        'remote-previous',
        'remote-jump-forward',
        'remote-jump-backward',
        'remote-seek',
    ];

    if (Platform.OS === 'android') {
        events.push('remote-skip', 'remote-duck', 'remote-set-rating');
    }

    registerBackendService(() => {
        return async function() {
            for (let i = 0; i < events.length; i++) {
                addEventListener(events[i], warpEventResponse.bind(null, handler, events[i]));
            }
        };
    });
}

// We'll declare each one of the constants and functions manually so IDEs can show a list of them
// We should also add documentation here, but I'll leave this task to another day

// States
module.exports.STATE_NONE = TrackPlayer.STATE_NONE;
module.exports.STATE_PLAYING = TrackPlayer.STATE_PLAYING;
module.exports.STATE_PAUSED = TrackPlayer.STATE_PAUSED;
module.exports.STATE_STOPPED = TrackPlayer.STATE_STOPPED;
module.exports.STATE_BUFFERING = TrackPlayer.STATE_BUFFERING;

// Capabilities
module.exports.CAPABILITY_PLAY = TrackPlayer.CAPABILITY_PLAY;
module.exports.CAPABILITY_PLAY_FROM_ID = TrackPlayer.CAPABILITY_PLAY_FROM_ID;
module.exports.CAPABILITY_PLAY_FROM_SEARCH = TrackPlayer.CAPABILITY_PLAY_FROM_SEARCH;
module.exports.CAPABILITY_PAUSE = TrackPlayer.CAPABILITY_PAUSE;
module.exports.CAPABILITY_STOP = TrackPlayer.CAPABILITY_STOP;
module.exports.CAPABILITY_SEEK_TO = TrackPlayer.CAPABILITY_SEEK_TO;
module.exports.CAPABILITY_SKIP = TrackPlayer.CAPABILITY_SKIP;
module.exports.CAPABILITY_SKIP_TO_NEXT = TrackPlayer.CAPABILITY_SKIP_TO_NEXT;
module.exports.CAPABILITY_SKIP_TO_PREVIOUS = TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS;
module.exports.CAPABILITY_JUMP_FORWARD = TrackPlayer.CAPABILITY_JUMP_FORWARD;
module.exports.CAPABILITY_JUMP_BACKWARD = TrackPlayer.CAPABILITY_JUMP_BACKWARD;
module.exports.CAPABILITY_SET_RATING = TrackPlayer.CAPABILITY_SET_RATING;

// Pitch algorithms
module.exports.PITCH_ALGORITHM_LINEAR = TrackPlayer.PITCH_ALGORITHM_LINEAR;
module.exports.PITCH_ALGORITHM_MUSIC = TrackPlayer.PITCH_ALGORITHM_MUSIC;
module.exports.PITCH_ALGORITHM_VOICE = TrackPlayer.PITCH_ALGORITHM_VOICE;

// Rating Types
module.exports.RATING_HEART = TrackPlayer.RATING_HEART;
module.exports.RATING_THUMBS_UP_DOWN = TrackPlayer.RATING_THUMBS_UP_DOWN;
module.exports.RATING_3_STARS = TrackPlayer.RATING_3_STARS;
module.exports.RATING_4_STARS = TrackPlayer.RATING_4_STARS;
module.exports.RATING_5_STARS = TrackPlayer.RATING_5_STARS;
module.exports.RATING_PERCENTAGE = TrackPlayer.RATING_PERCENTAGE;

// General
module.exports.setupPlayer = setupPlayer;
module.exports.destroy = TrackPlayer.destroy;
module.exports.updateOptions = updateOptions;
module.exports.registerEventHandler = registerEventHandler;
module.exports.registerBackendService = registerBackendService;
module.exports.addEventListener = addEventListener;

// Player Queue Commands
module.exports.add = add;
module.exports.remove = remove;
module.exports.skip = TrackPlayer.skip;
module.exports.getQueue = TrackPlayer.getQueue;
module.exports.skipToNext = TrackPlayer.skipToNext;
module.exports.skipToPrevious = TrackPlayer.skipToPrevious;
module.exports.removeUpcomingTracks = TrackPlayer.removeUpcomingTracks;

// Player Playback Commands
module.exports.reset = TrackPlayer.reset;
module.exports.play = TrackPlayer.play;
module.exports.pause = TrackPlayer.pause;
module.exports.stop = TrackPlayer.stop;
module.exports.seekTo = TrackPlayer.seekTo;
module.exports.setVolume = TrackPlayer.setVolume;
module.exports.setRate = TrackPlayer.setRate;

// Player Getters
module.exports.getTrack = TrackPlayer.getTrack;
module.exports.getCurrentTrack = TrackPlayer.getCurrentTrack;
module.exports.getVolume = TrackPlayer.getVolume;
module.exports.getDuration = TrackPlayer.getDuration;
module.exports.getPosition = TrackPlayer.getPosition;
module.exports.getBufferedPosition = TrackPlayer.getBufferedPosition;
module.exports.getState = TrackPlayer.getState;
module.exports.getRate = TrackPlayer.getRate;

// Components
module.exports.ProgressComponent = require('./ProgressComponent');
<commit_msg>[js] Added registerPlaybackService as an alias for registerBackendService<commit_after>import { Platform, AppRegistry, DeviceEventEmitter, NativeEventEmitter, NativeModules } from 'react-native';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';

const { TrackPlayerModule: TrackPlayer } = NativeModules;
const emitter = Platform.OS !== 'android' ? new NativeEventEmitter(TrackPlayer) : DeviceEventEmitter;

function resolveAsset(uri) {
    if(!uri) return undefined;
    return resolveAssetSource(uri);
}

function resolveUrl(url) {
    if(!url) return undefined;
    return resolveAssetSource(url) || url;
}

function setupPlayer(options) {
    return TrackPlayer.setupPlayer(options || {});
}

function updateOptions(data) {
    // Clone the object before modifying it, so we don't run into problems with immutable objects
    data = Object.assign({}, data);

    // Resolve the asset for each icon
    data.icon = resolveAsset(data.icon);
    data.playIcon = resolveAsset(data.playIcon);
    data.pauseIcon = resolveAsset(data.pauseIcon);
    data.stopIcon = resolveAsset(data.stopIcon);
    data.previousIcon = resolveAsset(data.previousIcon);
    data.nextIcon = resolveAsset(data.nextIcon);

    return TrackPlayer.updateOptions(data);
}

function add(tracks, insertBeforeId) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    for(let i = 0; i < tracks.length; i++) {
        // Clone the object before modifying it
        tracks[i] = Object.assign({}, tracks[i]);

        // Resolve the URLs
        tracks[i].url = resolveUrl(tracks[i].url);
        tracks[i].artwork = resolveUrl(tracks[i].artwork);

        // Cast ID's into strings
        tracks[i].id = `${tracks[i].id}`
    }

    return TrackPlayer.add(tracks, insertBeforeId);
}

function remove(tracks) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    return TrackPlayer.remove(tracks);
}

function registerPlaybackService(serviceFactory) {
    if (Platform.OS === 'android') {
        // Registers the headless task
        AppRegistry.registerHeadlessTask('TrackPlayer', serviceFactory);
    } else {
        // Initializes and runs the service in the next tick
        setImmediate(serviceFactory());
    }
}

function addEventListener(event, listener) {
    return emitter.addListener(event, listener);
}

function warpEventResponse(handler, event, payload) {
    // transform into the old format and return to handler
    const additionalKeys = payload || {};
    handler({ type: event, ...additionalKeys });
}

/**
 * @deprecated since version 1.0.1. Use addEventListener instead.
 */
function registerEventHandler(handler) {
    let events = [
        'playback-state',
        'playback-error',
        'playback-queue-ended',
        'playback-track-changed',

        'remote-play',
        'remote-pause',
        'remote-stop',
        'remote-next',
        'remote-previous',
        'remote-jump-forward',
        'remote-jump-backward',
        'remote-seek',
    ];

    if (Platform.OS === 'android') {
        events.push('remote-skip', 'remote-duck', 'remote-set-rating');
    }

    registerPlaybackService(() => {
        return async function() {
            for (let i = 0; i < events.length; i++) {
                addEventListener(events[i], warpEventResponse.bind(null, handler, events[i]));
            }
        };
    });
}

// We'll declare each one of the constants and functions manually so IDEs can show a list of them
// We should also add documentation here, but I'll leave this task to another day

// States
module.exports.STATE_NONE = TrackPlayer.STATE_NONE;
module.exports.STATE_PLAYING = TrackPlayer.STATE_PLAYING;
module.exports.STATE_PAUSED = TrackPlayer.STATE_PAUSED;
module.exports.STATE_STOPPED = TrackPlayer.STATE_STOPPED;
module.exports.STATE_BUFFERING = TrackPlayer.STATE_BUFFERING;

// Capabilities
module.exports.CAPABILITY_PLAY = TrackPlayer.CAPABILITY_PLAY;
module.exports.CAPABILITY_PLAY_FROM_ID = TrackPlayer.CAPABILITY_PLAY_FROM_ID;
module.exports.CAPABILITY_PLAY_FROM_SEARCH = TrackPlayer.CAPABILITY_PLAY_FROM_SEARCH;
module.exports.CAPABILITY_PAUSE = TrackPlayer.CAPABILITY_PAUSE;
module.exports.CAPABILITY_STOP = TrackPlayer.CAPABILITY_STOP;
module.exports.CAPABILITY_SEEK_TO = TrackPlayer.CAPABILITY_SEEK_TO;
module.exports.CAPABILITY_SKIP = TrackPlayer.CAPABILITY_SKIP;
module.exports.CAPABILITY_SKIP_TO_NEXT = TrackPlayer.CAPABILITY_SKIP_TO_NEXT;
module.exports.CAPABILITY_SKIP_TO_PREVIOUS = TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS;
module.exports.CAPABILITY_JUMP_FORWARD = TrackPlayer.CAPABILITY_JUMP_FORWARD;
module.exports.CAPABILITY_JUMP_BACKWARD = TrackPlayer.CAPABILITY_JUMP_BACKWARD;
module.exports.CAPABILITY_SET_RATING = TrackPlayer.CAPABILITY_SET_RATING;

// Pitch algorithms
module.exports.PITCH_ALGORITHM_LINEAR = TrackPlayer.PITCH_ALGORITHM_LINEAR;
module.exports.PITCH_ALGORITHM_MUSIC = TrackPlayer.PITCH_ALGORITHM_MUSIC;
module.exports.PITCH_ALGORITHM_VOICE = TrackPlayer.PITCH_ALGORITHM_VOICE;

// Rating Types
module.exports.RATING_HEART = TrackPlayer.RATING_HEART;
module.exports.RATING_THUMBS_UP_DOWN = TrackPlayer.RATING_THUMBS_UP_DOWN;
module.exports.RATING_3_STARS = TrackPlayer.RATING_3_STARS;
module.exports.RATING_4_STARS = TrackPlayer.RATING_4_STARS;
module.exports.RATING_5_STARS = TrackPlayer.RATING_5_STARS;
module.exports.RATING_PERCENTAGE = TrackPlayer.RATING_PERCENTAGE;

// General
module.exports.setupPlayer = setupPlayer;
module.exports.destroy = TrackPlayer.destroy;
module.exports.updateOptions = updateOptions;
module.exports.registerEventHandler = registerEventHandler;
module.exports.registerBackendService = registerPlaybackService;
module.exports.registerPlaybackService = registerPlaybackService;
module.exports.addEventListener = addEventListener;

// Player Queue Commands
module.exports.add = add;
module.exports.remove = remove;
module.exports.skip = TrackPlayer.skip;
module.exports.getQueue = TrackPlayer.getQueue;
module.exports.skipToNext = TrackPlayer.skipToNext;
module.exports.skipToPrevious = TrackPlayer.skipToPrevious;
module.exports.removeUpcomingTracks = TrackPlayer.removeUpcomingTracks;

// Player Playback Commands
module.exports.reset = TrackPlayer.reset;
module.exports.play = TrackPlayer.play;
module.exports.pause = TrackPlayer.pause;
module.exports.stop = TrackPlayer.stop;
module.exports.seekTo = TrackPlayer.seekTo;
module.exports.setVolume = TrackPlayer.setVolume;
module.exports.setRate = TrackPlayer.setRate;

// Player Getters
module.exports.getTrack = TrackPlayer.getTrack;
module.exports.getCurrentTrack = TrackPlayer.getCurrentTrack;
module.exports.getVolume = TrackPlayer.getVolume;
module.exports.getDuration = TrackPlayer.getDuration;
module.exports.getPosition = TrackPlayer.getPosition;
module.exports.getBufferedPosition = TrackPlayer.getBufferedPosition;
module.exports.getState = TrackPlayer.getState;
module.exports.getRate = TrackPlayer.getRate;

// Components
module.exports.ProgressComponent = require('./ProgressComponent');
<|endoftext|>