<commit_before>/* eslint-disable
    camelcase,
    handle-callback-err,
    no-return-assign,
    no-undef,
    no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
 * decaffeinate suggestions:
 * DS101: Remove unnecessary use of Array.from
 * DS102: Remove unnecessary code created because of implicit returns
 * DS202: Simplify dynamic range loops
 * DS205: Consider reworking code to avoid use of IIFEs
 * DS207: Consider shorter variations of null checks
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
const DocUpdaterClient = require("../../acceptance/coffee/helpers/DocUpdaterClient");
// MockTrackChangesApi = require "../../acceptance/js/helpers/MockTrackChangesApi"
// MockWebApi = require "../../acceptance/js/helpers/MockWebApi"
const assert = require("assert");
const async = require("async");

const insert = function(string, pos, content) {
	const result = string.slice(0, pos) + content + string.slice(pos);
	return result;
};

const transform = function(op1, op2) {
	if (op2.p < op1.p) {
		return {
			p: op1.p + op2.i.length,
			i: op1.i
		};
	} else {
		return op1;
	}
};

class StressTestClient {
	constructor(options) {
		if (options == null) { options = {}; }
		this.options = options;
		if (this.options.updateDelay == null) { this.options.updateDelay = 200; }
		this.project_id = this.options.project_id || DocUpdaterClient.randomId();
		this.doc_id = this.options.doc_id || DocUpdaterClient.randomId();
		this.pos = this.options.pos || 0;
		this.content = this.options.content || "";

		this.client_id = DocUpdaterClient.randomId();
		this.version = this.options.version || 0;
		this.inflight_op = null;
		this.charCode = 0;

		this.counts = {
			conflicts: 0,
			local_updates: 0,
			remote_updates: 0,
			max_delay: 0
		};

		DocUpdaterClient.subscribeToAppliedOps((channel, update) => {
			update = JSON.parse(update);
			if (update.error != null) {
				console.error(new Error(`Error from server: '${update.error}'`));
				return;
			}
			if (update.doc_id === this.doc_id) {
				return this.processReply(update);
			}
		});
	}

	sendUpdate() {
		const data = String.fromCharCode(65 + (this.charCode++ % 26));
		this.content = insert(this.content, this.pos, data);
		this.inflight_op = {
			i: data,
			p: this.pos++
		};
		this.resendUpdate();
		return this.inflight_op_sent = Date.now();
	}

	resendUpdate() {
		assert(this.inflight_op != null);
		DocUpdaterClient.sendUpdate(
			this.project_id, this.doc_id,
			{
				doc: this.doc_id,
				op: [this.inflight_op],
				v: this.version,
				meta: {
					source: this.client_id
				},
				dupIfSource: [this.client_id]
			}
		);
		return this.update_timer = setTimeout(() => {
			console.log(`[${new Date()}] \t[${this.client_id.slice(0,4)}] WARN: Resending update after 5 seconds`);
			return this.resendUpdate();
		}
		, 5000);
	}

	processReply(update) {
		if (update.op.v !== this.version) {
			if (update.op.v < this.version) {
				console.log(`[${new Date()}] \t[${this.client_id.slice(0,4)}] WARN: Duplicate ack (already seen version)`);
				return;
			} else {
				console.error(`[${new Date()}] \t[${this.client_id.slice(0,4)}] ERROR: Version jumped ahead (client: ${this.version}, op: ${update.op.v})`);
			}
		}
		this.version++;
		if (update.op.meta.source === this.client_id) {
			if (this.inflight_op != null) {
				this.counts.local_updates++;
				this.inflight_op = null;
				clearTimeout(this.update_timer);
				const delay = Date.now() - this.inflight_op_sent;
				this.counts.max_delay = Math.max(this.counts.max_delay, delay);
				return this.continue();
			} else {
				return console.log(`[${new Date()}] \t[${this.client_id.slice(0,4)}] WARN: Duplicate ack`);
			}
		} else {
			assert(update.op.op.length === 1);
			this.counts.remote_updates++;
			let external_op = update.op.op[0];
			if (this.inflight_op != null) {
				this.counts.conflicts++;
				this.inflight_op = transform(this.inflight_op, external_op);
				external_op = transform(external_op, this.inflight_op);
			}
			if (external_op.p < this.pos) {
				this.pos += external_op.i.length;
			}
			return this.content = insert(this.content, external_op.p, external_op.i);
		}
	}

	continue() {
		if (this.updateCount > 0) {
			this.updateCount--;
			return setTimeout(() => {
				return this.sendUpdate();
			}
			, this.options.updateDelay * ( 0.5 + Math.random() ));
		} else {
			return this.updateCallback();
		}
	}

	runForNUpdates(n, callback) {
		if (callback == null) { callback = function(error) {}; }
		this.updateCallback = callback;
		this.updateCount = n;
		return this.continue();
	}

	check(callback) {
		if (callback == null) { callback = function(error) {}; }
		return DocUpdaterClient.getDoc(this.project_id, this.doc_id, (error, res, body) => {
			if (error != null) { throw error; }
			if ((body.lines == null)) {
				return console.error(`[${new Date()}] \t[${this.client_id.slice(0,4)}] ERROR: Invalid response from get doc (${doc_id})`, body);
			}
			const content = body.lines.join("\n");
			const {
                version
            } = body;
			if (content !== this.content) {
				if (version === this.version) {
					console.error(`[${new Date()}] \t[${this.client_id.slice(0,4)}] Error: Client content does not match server.`);
					console.error(`Server: ${content.split('a')}`);
					console.error(`Client: ${this.content.split('a')}`);
				} else {
					console.error(`[${new Date()}] \t[${this.client_id.slice(0,4)}] Error: Version mismatch (Server: '${version}', Client: '${this.version}')`);
				}
			}

			if (!this.isContentValid(this.content)) {
				const iterable = this.content.split("");
				for (let i = 0; i < iterable.length; i++) {
					const chunk = iterable[i];
					if ((chunk != null) && (chunk !== "a")) {
						console.log(chunk, i);
					}
				}
				throw new Error("bad content");
			}
			return callback();
		});
	}

	isChunkValid(chunk) {
		const char = 0;
		for (let i = 0; i < chunk.length; i++) {
			const letter = chunk[i];
			if (letter.charCodeAt(0) !== (65 + (i % 26))) {
				console.error(`[${new Date()}] \t[${this.client_id.slice(0,4)}] Invalid Chunk:`, chunk);
				return false;
			}
		}
		return true;
	}

	isContentValid(content) {
		for (const chunk of Array.from(content.split('a'))) {
			if ((chunk != null) && (chunk !== "")) {
				if (!this.isChunkValid(chunk)) {

					console.error(`[${new Date()}] \t[${this.client_id.slice(0,4)}] Invalid content`, content);
					return false;
				}
			}
		}
		return true;
	}
}

const checkDocument = function(project_id, doc_id, clients, callback) {
	if (callback == null) { callback = function(error) {}; }
	const jobs = clients.map(client => cb => client.check(cb));
	return async.parallel(jobs, callback);
};

const printSummary = function(doc_id, clients) {
	const slot = require('cluster-key-slot');
	const now = new Date();
	console.log(`[${now}] [${doc_id.slice(0,4)} (slot: ${slot(doc_id)})] ${clients.length} clients...`);
	return (() => {
		const result = [];
		for (const client of Array.from(clients)) {
			console.log(`[${now}] \t[${client.client_id.slice(0,4)}] { local: ${client.counts.local_updates }, remote: ${client.counts.remote_updates}, conflicts: ${client.counts.conflicts}, max_delay: ${client.counts.max_delay} }`);
			result.push(client.counts = {
				local_updates: 0,
				remote_updates: 0,
				conflicts: 0,
				max_delay: 0
			});
		}
		return result;
	})();
};

const CLIENT_COUNT = parseInt(process.argv[2], 10);
const UPDATE_DELAY = parseInt(process.argv[3], 10);
const SAMPLE_INTERVAL = parseInt(process.argv[4], 10);

for (const doc_and_project_id of Array.from(process.argv.slice(5))) {
	(function(doc_and_project_id) {
		const [project_id, doc_id] = Array.from(doc_and_project_id.split(":"));
		console.log({project_id, doc_id});
		return DocUpdaterClient.setDocLines(project_id, doc_id, [(new Array(CLIENT_COUNT + 2)).join('a')], null, null, (error) => {
			if (error != null) { throw error; }
			return DocUpdaterClient.getDoc(project_id, doc_id, (error, res, body) => {
				let runBatch;
				if (error != null) { throw error; }
				if ((body.lines == null)) {
					return console.error(`[${new Date()}] ERROR: Invalid response from get doc (${doc_id})`, body);
				}
				const content = body.lines.join("\n");
				const {
                    version
                } = body;

				const clients = [];
				for (let pos = 1, end = CLIENT_COUNT, asc = end >= 1; asc ? pos <= end : pos >= end; asc ? pos++ : pos--) {
					(function(pos) {
						const client = new StressTestClient({doc_id, project_id, content, pos, version, updateDelay: UPDATE_DELAY});
						return clients.push(client);
					})(pos);
				}

				return (runBatch = function() {
					const jobs = clients.map(client => cb => client.runForNUpdates(SAMPLE_INTERVAL / UPDATE_DELAY, cb));
					return async.parallel(jobs, (error) => {
						if (error != null) { throw error; }
						printSummary(doc_id, clients);
						return checkDocument(project_id, doc_id, clients, (error) => {
							if (error != null) { throw error; }
							return runBatch();
						});
					});
				})();
			});
		});
	})(doc_and_project_id);
}
<commit_msg>prettier: convert test/stress decaffeinated files to Prettier format<commit_after>/* eslint-disable
    camelcase,
    handle-callback-err,
    no-return-assign,
    no-undef,
    no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
 * decaffeinate suggestions:
 * DS101: Remove unnecessary use of Array.from
 * DS102: Remove unnecessary code created because of implicit returns
 * DS202: Simplify dynamic range loops
 * DS205: Consider reworking code to avoid use of IIFEs
 * DS207: Consider shorter variations of null checks
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
const DocUpdaterClient = require('../../acceptance/coffee/helpers/DocUpdaterClient')
// MockTrackChangesApi = require "../../acceptance/js/helpers/MockTrackChangesApi"
// MockWebApi = require "../../acceptance/js/helpers/MockWebApi"
const assert = require('assert')
const async = require('async')

const insert = function (string, pos, content) {
  const result = string.slice(0, pos) + content + string.slice(pos)
  return result
}

const transform = function (op1, op2) {
  if (op2.p < op1.p) {
    return {
      p: op1.p + op2.i.length,
      i: op1.i
    }
  } else {
    return op1
  }
}

class StressTestClient {
  constructor(options) {
    if (options == null) {
      options = {}
    }
    this.options = options
    if (this.options.updateDelay == null) {
      this.options.updateDelay = 200
    }
    this.project_id = this.options.project_id || DocUpdaterClient.randomId()
    this.doc_id = this.options.doc_id || DocUpdaterClient.randomId()
    this.pos = this.options.pos || 0
    this.content = this.options.content || ''

    this.client_id = DocUpdaterClient.randomId()
    this.version = this.options.version || 0
    this.inflight_op = null
    this.charCode = 0

    this.counts = {
      conflicts: 0,
      local_updates: 0,
      remote_updates: 0,
      max_delay: 0
    }

    DocUpdaterClient.subscribeToAppliedOps((channel, update) => {
      update = JSON.parse(update)
      if (update.error != null) {
        console.error(new Error(`Error from server: '${update.error}'`))
        return
      }
      if (update.doc_id === this.doc_id) {
        return this.processReply(update)
      }
    })
  }

  sendUpdate() {
    const data = String.fromCharCode(65 + (this.charCode++ % 26))
    this.content = insert(this.content, this.pos, data)
    this.inflight_op = {
      i: data,
      p: this.pos++
    }
    this.resendUpdate()
    return (this.inflight_op_sent = Date.now())
  }

  resendUpdate() {
    assert(this.inflight_op != null)
    DocUpdaterClient.sendUpdate(this.project_id, this.doc_id, {
      doc: this.doc_id,
      op: [this.inflight_op],
      v: this.version,
      meta: {
        source: this.client_id
      },
      dupIfSource: [this.client_id]
    })
    return (this.update_timer = setTimeout(() => {
      console.log(
        `[${new Date()}] \t[${this.client_id.slice(
          0,
          4
        )}] WARN: Resending update after 5 seconds`
      )
      return this.resendUpdate()
    }, 5000))
  }

  processReply(update) {
    if (update.op.v !== this.version) {
      if (update.op.v < this.version) {
        console.log(
          `[${new Date()}] \t[${this.client_id.slice(
            0,
            4
          )}] WARN: Duplicate ack (already seen version)`
        )
        return
      } else {
        console.error(
          `[${new Date()}] \t[${this.client_id.slice(
            0,
            4
          )}] ERROR: Version jumped ahead (client: ${this.version}, op: ${
            update.op.v
          })`
        )
      }
    }
    this.version++
    if (update.op.meta.source === this.client_id) {
      if (this.inflight_op != null) {
        this.counts.local_updates++
        this.inflight_op = null
        clearTimeout(this.update_timer)
        const delay = Date.now() - this.inflight_op_sent
        this.counts.max_delay = Math.max(this.counts.max_delay, delay)
        return this.continue()
      } else {
        return console.log(
          `[${new Date()}] \t[${this.client_id.slice(
            0,
            4
          )}] WARN: Duplicate ack`
        )
      }
    } else {
      assert(update.op.op.length === 1)
      this.counts.remote_updates++
      let external_op = update.op.op[0]
      if (this.inflight_op != null) {
        this.counts.conflicts++
        this.inflight_op = transform(this.inflight_op, external_op)
        external_op = transform(external_op, this.inflight_op)
      }
      if (external_op.p < this.pos) {
        this.pos += external_op.i.length
      }
      return (this.content = insert(this.content, external_op.p, external_op.i))
    }
  }

  continue() {
    if (this.updateCount > 0) {
      this.updateCount--
      return setTimeout(() => {
        return this.sendUpdate()
      }, this.options.updateDelay * (0.5 + Math.random()))
    } else {
      return this.updateCallback()
    }
  }

  runForNUpdates(n, callback) {
    if (callback == null) {
      callback = function (error) {}
    }
    this.updateCallback = callback
    this.updateCount = n
    return this.continue()
  }

  check(callback) {
    if (callback == null) {
      callback = function (error) {}
    }
    return DocUpdaterClient.getDoc(
      this.project_id,
      this.doc_id,
      (error, res, body) => {
        if (error != null) {
          throw error
        }
        if (body.lines == null) {
          return console.error(
            `[${new Date()}] \t[${this.client_id.slice(
              0,
              4
            )}] ERROR: Invalid response from get doc (${doc_id})`,
            body
          )
        }
        const content = body.lines.join('\n')
        const { version } = body
        if (content !== this.content) {
          if (version === this.version) {
            console.error(
              `[${new Date()}] \t[${this.client_id.slice(
                0,
                4
              )}] Error: Client content does not match server.`
            )
            console.error(`Server: ${content.split('a')}`)
            console.error(`Client: ${this.content.split('a')}`)
          } else {
            console.error(
              `[${new Date()}] \t[${this.client_id.slice(
                0,
                4
              )}] Error: Version mismatch (Server: '${version}', Client: '${
                this.version
              }')`
            )
          }
        }

        if (!this.isContentValid(this.content)) {
          const iterable = this.content.split('')
          for (let i = 0; i < iterable.length; i++) {
            const chunk = iterable[i]
            if (chunk != null && chunk !== 'a') {
              console.log(chunk, i)
            }
          }
          throw new Error('bad content')
        }
        return callback()
      }
    )
  }

  isChunkValid(chunk) {
    const char = 0
    for (let i = 0; i < chunk.length; i++) {
      const letter = chunk[i]
      if (letter.charCodeAt(0) !== 65 + (i % 26)) {
        console.error(
          `[${new Date()}] \t[${this.client_id.slice(0, 4)}] Invalid Chunk:`,
          chunk
        )
        return false
      }
    }
    return true
  }

  isContentValid(content) {
    for (const chunk of Array.from(content.split('a'))) {
      if (chunk != null && chunk !== '') {
        if (!this.isChunkValid(chunk)) {
          console.error(
            `[${new Date()}] \t[${this.client_id.slice(0, 4)}] Invalid content`,
            content
          )
          return false
        }
      }
    }
    return true
  }
}

const checkDocument = function (project_id, doc_id, clients, callback) {
  if (callback == null) {
    callback = function (error) {}
  }
  const jobs = clients.map((client) => (cb) => client.check(cb))
  return async.parallel(jobs, callback)
}

const printSummary = function (doc_id, clients) {
  const slot = require('cluster-key-slot')
  const now = new Date()
  console.log(
    `[${now}] [${doc_id.slice(0, 4)} (slot: ${slot(doc_id)})] ${
      clients.length
    } clients...`
  )
  return (() => {
    const result = []
    for (const client of Array.from(clients)) {
      console.log(
        `[${now}] \t[${client.client_id.slice(0, 4)}] { local: ${
          client.counts.local_updates
        }, remote: ${client.counts.remote_updates}, conflicts: ${
          client.counts.conflicts
        }, max_delay: ${client.counts.max_delay} }`
      )
      result.push(
        (client.counts = {
          local_updates: 0,
          remote_updates: 0,
          conflicts: 0,
          max_delay: 0
        })
      )
    }
    return result
  })()
}

const CLIENT_COUNT = parseInt(process.argv[2], 10)
const UPDATE_DELAY = parseInt(process.argv[3], 10)
const SAMPLE_INTERVAL = parseInt(process.argv[4], 10)

for (const doc_and_project_id of Array.from(process.argv.slice(5))) {
  ;(function (doc_and_project_id) {
    const [project_id, doc_id] = Array.from(doc_and_project_id.split(':'))
    console.log({ project_id, doc_id })
    return DocUpdaterClient.setDocLines(
      project_id,
      doc_id,
      [new Array(CLIENT_COUNT + 2).join('a')],
      null,
      null,
      (error) => {
        if (error != null) {
          throw error
        }
        return DocUpdaterClient.getDoc(
          project_id,
          doc_id,
          (error, res, body) => {
            let runBatch
            if (error != null) {
              throw error
            }
            if (body.lines == null) {
              return console.error(
                `[${new Date()}] ERROR: Invalid response from get doc (${doc_id})`,
                body
              )
            }
            const content = body.lines.join('\n')
            const { version } = body

            const clients = []
            for (
              let pos = 1, end = CLIENT_COUNT, asc = end >= 1;
              asc ? pos <= end : pos >= end;
              asc ? pos++ : pos--
            ) {
              ;(function (pos) {
                const client = new StressTestClient({
                  doc_id,
                  project_id,
                  content,
                  pos,
                  version,
                  updateDelay: UPDATE_DELAY
                })
                return clients.push(client)
              })(pos)
            }

            return (runBatch = function () {
              const jobs = clients.map((client) => (cb) =>
                client.runForNUpdates(SAMPLE_INTERVAL / UPDATE_DELAY, cb)
              )
              return async.parallel(jobs, (error) => {
                if (error != null) {
                  throw error
                }
                printSummary(doc_id, clients)
                return checkDocument(project_id, doc_id, clients, (error) => {
                  if (error != null) {
                    throw error
                  }
                  return runBatch()
                })
              })
            })()
          }
        )
      }
    )
  })(doc_and_project_id)
}
<|endoftext|>


<commit_before>'use babel';

/**
 * Dependencies
 */

import exec from './exec.js';

/**
 * Interface
 */

export default {
  activate() {
    require('atom-package-deps').install('fast-eslint');
  },

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

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

        return exec(filePath, fileText).then(report => {
          if (!report || !report.results) return [];

          return report.results[0].messages.map(({ column, line, message, ruleId, severity }) => {
            const range = helpers.rangeFromLineNumber(TextEditor, line - 1);
            if (column) range[0][1] = column - 1;
            if (column > range[1][1]) range[1][1] = column - 1;

            return {
              filePath,
              range,
              type: severity === 1 ? 'Warning' : 'Error',
              html: `<span class="badge badge-flexible">${ruleId || 'Fatal'}</span> ${message}`,
            };
          });
        });
      },
    };
  },
};
<commit_msg>fix(linter): fix linter config to file scope only<commit_after>'use babel';

/**
 * Dependencies
 */

import exec from './exec.js';

/**
 * Interface
 */

export default {
  activate() {
    require('atom-package-deps').install('fast-eslint');
  },

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

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

        return exec(filePath, fileText).then(report => {
          if (!report || !report.results) return [];

          return report.results[0].messages.map(({ column, line, message, ruleId, severity }) => {
            const range = helpers.rangeFromLineNumber(TextEditor, line - 1);
            if (column) range[0][1] = column - 1;
            if (column > range[1][1]) range[1][1] = column - 1;

            return {
              filePath,
              range,
              type: severity === 1 ? 'Warning' : 'Error',
              html: `<span class="badge badge-flexible">${ruleId || 'Fatal'}</span> ${message}`,
            };
          });
        });
      },
    };
  },
};
<|endoftext|>


<commit_before>/*
 * nikko
 * https://github.com/goliatone/nikko
 *
 * Copyright (c) 2015 goliatone
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var extend = require('gextend');

var DEFAULTS = {
    autoinitialize: true
};

function Nikko(config){
    config = extend({}, DEFAULTS, config);
    if(config.autoinitialize) this.init(config);
}

/*
 * Unit testing stuff and such.
 */
Nikko.packagePath = '../package.json';
Nikko.packageObject = require(Nikko.packagePath);

Nikko.prototype.init = function(config){
    if(this.initialized) return
    this.initialized = true;

    extend(this, DEFAULTS, config);

    this.basePath = path.resolve(path.join(__dirname, '..'));
    this.binPath = path.join(this.basePath, 'bin');
    this.pluginPath = path.join(this.basePath, 'plugins');
    this.modulePath = path.join(this.basePath, 'node_modules');

    this.buildConfig();
};

Nikko.prototype.buildConfig = function(){
    var Config = require('./utils/config');
    this.cloader = new Config();
    this.cloader.load('nikko', {});
    this.config = this.cloader.config;
    return this;
};

/**
 * Function that registers a plugin, usually
 * called from `install` command.
 * @param  {String} plugin Plugin id
 * @return {this}
 */
Nikko.prototype.registerPlugin = function(plugin){
    // https://github.com/vesln/package
    // save package plugin
    var readJson = require('read-package-json');

    // readJson(filename, [logFunction=noop], [strict=false], cb)
    var pkgPath = path.join(this.basePath, 'package.json');
    console.log('READ PACKAGE', pkgPath);
    readJson(pkgPath, this.logger.error, false, function (er, data) {
      if (er) {
        console.error("There was an error reading the file");
        return
      }
      console.error('the package data is', data);
      if(!data.plugins) data.plugins = [];

      //Plugin should provide a register method? Or should we
      //get this form plugin pakckage? package of plugin should
      //provide name + command + description + exported files which
      //get moved on install
      var plugInfo = {};
      plugInfo[plugin] = ['list', 'List plugin'];
      data.plugins.push(plugInfo);
      var fs = require('fs');
      fs.writeFileSync(pkgPath, JSON.stringify(data, null, 2));

      //After we have moved the plugin, we should cd to plugin dir and npm i
    });

    return this;
};

///////////
// CONFIG
///////////
///A) When we create a project we check for .nikkorc
/// if its not there we make a new one
Nikko.prototype.createConfig = function(){

};

Nikko.extract = function(obj, props){
    var out = {};
    props.forEach(function(key){
        if(props[key] === undefined) return;
        out[key] = props[key];
    });
    return out;
};
///////////

/**
 * Executes a plugin. It will look for the
 * plugin in the directory containing installed
 * plugins.
 * Command id is the command name that we enter on
 * terminal, which then maps to a file inside `bin`
 * following the convention **nikko-**{command}.
 *
 *
 * @param  {String} command Command id
 * @param  {Object} config  Configuration obj
 * @return {Nikko}          Nikko instance.
 */
Nikko.prototype.execute = function(command, config){
    var module = path.join(this.pluginPath, 'nikko-' + command);

    //Extract the config for this command:
    //TODO: move to config manager.
    config = extend({}, this.config[command], config);

    try {
        var plugin = require(module);
        plugin(config, this);
    } catch(e){
        //we should check if we have it installed.
        this.logger.error('Error executing command\n\n'+e.message);
    }
};

/**
 * Logger facility. By default
 * exposes `console`
 * @type {Function}
 */
Nikko.prototype.logger = console;

/**
 * Execute plugin
 * @param  {String} command Command id
 * @param  {Object} config  Configuration obj
 * @return {Nikko}          Nikko instance.
 */
Nikko.execute = function(command, config){
    var nikko = new Nikko();
    nikko.execute(command, config);
    return nikko;
};

module.exports = Nikko;
<commit_msg>LIB: Added getConfig, refactor how we handle config.<commit_after>/*
 * nikko
 * https://github.com/goliatone/nikko
 *
 * Copyright (c) 2015 goliatone
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var extend = require('gextend');

var DEFAULTS = {
    autoinitialize: true
};

function Nikko(config){
    config = extend({}, DEFAULTS, config);
    if(config.autoinitialize) this.init(config);
}

/*
 * Unit testing stuff and such.
 */
Nikko.packagePath = '../package.json';
Nikko.packageObject = require(Nikko.packagePath);

Nikko.prototype.init = function(config){
    if(this.initialized) return
    this.initialized = true;

    extend(this, DEFAULTS, config);

    this.basePath = path.resolve(path.join(__dirname, '..'));
    this.binPath = path.join(this.basePath, 'bin');
    this.pluginPath = path.join(this.basePath, 'plugins');
    this.modulePath = path.join(this.basePath, 'node_modules');

    this.buildConfig();
};

Nikko.prototype.buildConfig = function(){
    var Config = require('./utils/config');
    this.cloader = new Config();
    this.cloader.load('nikko', {});
    this.config = this.cloader.config;
    return this;
};

Nikko.prototype.getConfig = function(namespace){
    //TODO: Do this for realz, keypath etc. GConfig for node?
    if(namespace) return this.config[namespace];
    return this.config;
}

/**
 * Function that registers a plugin, usually
 * called from `install` command.
 * @param  {String} plugin Plugin id
 * @return {this}
 */
Nikko.prototype.registerPlugin = function(plugin){
    // https://github.com/vesln/package
    // save package plugin
    var readJson = require('read-package-json');

    // readJson(filename, [logFunction=noop], [strict=false], cb)
    var pkgPath = path.join(this.basePath, 'package.json');
    console.log('READ PACKAGE', pkgPath);
    readJson(pkgPath, this.logger.error, false, function (er, data) {
      if (er) {
        console.error("There was an error reading the file");
        return
      }
      console.error('the package data is', data);
      if(!data.plugins) data.plugins = [];

      //Plugin should provide a register method? Or should we
      //get this form plugin pakckage? package of plugin should
      //provide name + command + description + exported files which
      //get moved on install
      var plugInfo = {};
      plugInfo[plugin] = ['list', 'List plugin'];
      data.plugins.push(plugInfo);
      var fs = require('fs');
      fs.writeFileSync(pkgPath, JSON.stringify(data, null, 2));

      //After we have moved the plugin, we should cd to plugin dir and npm i
    });

    return this;
};

///////////
// CONFIG
///////////
///A) When we create a project we check for .nikkorc
/// if its not there we make a new one
Nikko.prototype.createConfig = function(){

};

Nikko.extract = function(obj, props){
    var out = {};
    props.forEach(function(key){
        if(props[key] === undefined) return;
        out[key] = props[key];
    });
    return out;
};
///////////

/**
 * Executes a plugin. It will look for the
 * plugin in the directory containing installed
 * plugins.
 * Command id is the command name that we enter on
 * terminal, which then maps to a file inside `bin`
 * following the convention **nikko-**{command}.
 *
 *
 * @param  {String} command Command id
 * @param  {Object} config  Configuration obj
 * @return {Nikko}          Nikko instance.
 */
Nikko.prototype.execute = function(command, config){
    var module = path.join(this.pluginPath, 'nikko-' + command);

    //Extract the config for this command:
    //TODO: move to config manager.
    config = extend({}, this.config[command], config);

    try {
        var plugin = require(module);
        plugin(config, this);
    } catch(e){
        //we should check if we have it installed.
        this.logger.error('Error executing command '+ module + '\n\n' + e.message);
    }
};

/**
 * Logger facility. By default
 * exposes `console`
 * @type {Function}
 */
Nikko.prototype.logger = console;

/**
 * Execute plugin
 * @param  {String} command Command id
 * @param  {Object} config  Configuration obj
 * @return {Nikko}          Nikko instance.
 */
Nikko.execute = function(command, config){
    var nikko = new Nikko();
    nikko.execute(command, config);
    return nikko;
};

module.exports = Nikko;
<|endoftext|>


<commit_before>var fs = require( 'fs' )
  , path = require( 'path' )
  , mime = require( 'mime' )
  , extract = require( './extract' )
  , os = require( 'os' )
  , got = require( 'got' )
  , tmpDir = os.tmpdir()
  ;

function _genRandom() {
  return Math.floor( ( Math.random() * 100000000000 ) + 1 );
}

function _extractWithType( type, filePath, options, cb ) {
  fs.exists( filePath, function( exists ) {
    if ( exists ) {
      extract( type, filePath, options, cb );
    } else {
      cb( new Error( 'File at path [[ ' + filePath + ' ]] does not exist.' ), null );
    }
  });
}

function _returnArgsError( _args ) {
  var args = Array.prototype.slice.call( _args )
    , callback
    ;

  args.forEach( function( parm ) {
    if ( parm && typeof parm === 'function' ) {
      callback = parm;
    }
  });

  if ( callback ) {
    callback( new Error( 'Incorrect parameters passed to textract.' ), null );
  } else {
    // eslint-disable-next-line no-console
    console.error( 'textract could not find a callback function to execute.' );
  }
}

function _writeBufferToDisk( buff, cb ) {
  var fullPath = path.join( tmpDir, 'textract_file_' + _genRandom() );

  fs.open( fullPath, 'w', function( err, fd ) {
    if ( err ) {
      throw new Error( 'error opening temp file: ' + err );
    } else {
      fs.write( fd, buff, 0, buff.length, null, function( err2 ) {
        if ( err2 ) {
          throw new Error( 'error writing temp file: ' + err2 );
        } else {
          fs.close( fd, function() {
            cb( fullPath );
          });
        }
      });
    }
  });
}

function fromFileWithMimeAndPath( type, filePath, options, cb ) {
  var called = false;

  if ( typeof type === 'string' && typeof filePath === 'string' ) {
    if ( typeof cb === 'function' && typeof options === 'object' ) {
      // (mimeType, filePath, options, callback)
      _extractWithType( type, filePath, options, cb );
      called = true;
    } else if ( typeof options === 'function' && cb === undefined ) {
      // (mimeType, filePath, callback)
      _extractWithType( type, filePath, {}, options );
      called = true;
    }
  }

  if ( !called ) {
    _returnArgsError( arguments );
  }
}

function fromFileWithPath( filePath, options, cb ) {
  var type;
  if ( typeof filePath === 'string' &&
       ( typeof options === 'function' || typeof cb === 'function' ) ) {
    type = ( options && options.typeOverride ) || mime.lookup( filePath );
    fromFileWithMimeAndPath( type, filePath, options, cb );
  } else {
    _returnArgsError( arguments );
  }
}

// eslint-disable-next-line no-unused-vars
function fromBufferWithMime( type, bufferContent, options, cb, withPath ) {
  if ( typeof type === 'string' &&
       bufferContent &&
       bufferContent instanceof Buffer &&
       ( typeof options === 'function' || typeof cb === 'function' ) ) {
    _writeBufferToDisk( bufferContent, function( newPath ) {
      fromFileWithMimeAndPath( type, newPath, options, cb );
    });
  } else {
    _returnArgsError( arguments );
  }
}

function fromBufferWithName( filePath, bufferContent, options, cb ) {
  var type;
  if ( typeof filePath === 'string' ) {
    type = mime.lookup( filePath );
    fromBufferWithMime( type, bufferContent, options, cb, true );
  } else {
    _returnArgsError( arguments );
  }
}

function fromUrl( url, options, cb ) {
  var urlNoQueryParams, extname, filePath, fullFilePath, file;

  if ( typeof url === 'string' ) {
    options = options || {};
    urlNoQueryParams = url.split( '?' )[0];
    extname = path.extname( urlNoQueryParams );
    filePath = _genRandom() + urlNoQueryParams.replace( /[^\w\s]/gi, '' ) + extname;
    fullFilePath = path.join( tmpDir, filePath );
    file = fs.createWriteStream( fullFilePath );
    file.on( 'finish', function() {
      fromFileWithPath( fullFilePath, options, cb );
    });

    got( url )
      .on( 'response', function( response ) {
        // allows for overriding by the developer or automatically
        // populating based on server response.
        if ( !options.typeOverride ) {
          options.typeOverride = response.headers['content-type'].split( /;/ )[0];
        }
      })
      .pipe( file );
  } else {
    _returnArgsError( arguments );
  }
}

module.exports = {
  fromFileWithPath: fromFileWithPath,
  fromFileWithMimeAndPath: fromFileWithMimeAndPath,
  fromBufferWithName: fromBufferWithName,
  fromBufferWithMime: fromBufferWithMime,
  fromUrl: fromUrl
};
<commit_msg>add got library error handling<commit_after>var fs = require( 'fs' )
  , path = require( 'path' )
  , mime = require( 'mime' )
  , extract = require( './extract' )
  , os = require( 'os' )
  , got = require( 'got' )
  , tmpDir = os.tmpdir()
  ;

function _genRandom() {
  return Math.floor( ( Math.random() * 100000000000 ) + 1 );
}

function _extractWithType( type, filePath, options, cb ) {
  fs.exists( filePath, function( exists ) {
    if ( exists ) {
      extract( type, filePath, options, cb );
    } else {
      cb( new Error( 'File at path [[ ' + filePath + ' ]] does not exist.' ), null );
    }
  });
}

function _returnArgsError( _args ) {
  var args = Array.prototype.slice.call( _args )
    , callback
    ;

  args.forEach( function( parm ) {
    if ( parm && typeof parm === 'function' ) {
      callback = parm;
    }
  });

  if ( callback ) {
    callback( new Error( 'Incorrect parameters passed to textract.' ), null );
  } else {
    // eslint-disable-next-line no-console
    console.error( 'textract could not find a callback function to execute.' );
  }
}

function _writeBufferToDisk( buff, cb ) {
  var fullPath = path.join( tmpDir, 'textract_file_' + _genRandom() );

  fs.open( fullPath, 'w', function( err, fd ) {
    if ( err ) {
      throw new Error( 'error opening temp file: ' + err );
    } else {
      fs.write( fd, buff, 0, buff.length, null, function( err2 ) {
        if ( err2 ) {
          throw new Error( 'error writing temp file: ' + err2 );
        } else {
          fs.close( fd, function() {
            cb( fullPath );
          });
        }
      });
    }
  });
}

function fromFileWithMimeAndPath( type, filePath, options, cb ) {
  var called = false;

  if ( typeof type === 'string' && typeof filePath === 'string' ) {
    if ( typeof cb === 'function' && typeof options === 'object' ) {
      // (mimeType, filePath, options, callback)
      _extractWithType( type, filePath, options, cb );
      called = true;
    } else if ( typeof options === 'function' && cb === undefined ) {
      // (mimeType, filePath, callback)
      _extractWithType( type, filePath, {}, options );
      called = true;
    }
  }

  if ( !called ) {
    _returnArgsError( arguments );
  }
}

function fromFileWithPath( filePath, options, cb ) {
  var type;
  if ( typeof filePath === 'string' &&
       ( typeof options === 'function' || typeof cb === 'function' ) ) {
    type = ( options && options.typeOverride ) || mime.lookup( filePath );
    fromFileWithMimeAndPath( type, filePath, options, cb );
  } else {
    _returnArgsError( arguments );
  }
}

// eslint-disable-next-line no-unused-vars
function fromBufferWithMime( type, bufferContent, options, cb, withPath ) {
  if ( typeof type === 'string' &&
       bufferContent &&
       bufferContent instanceof Buffer &&
       ( typeof options === 'function' || typeof cb === 'function' ) ) {
    _writeBufferToDisk( bufferContent, function( newPath ) {
      fromFileWithMimeAndPath( type, newPath, options, cb );
    });
  } else {
    _returnArgsError( arguments );
  }
}

function fromBufferWithName( filePath, bufferContent, options, cb ) {
  var type;
  if ( typeof filePath === 'string' ) {
    type = mime.lookup( filePath );
    fromBufferWithMime( type, bufferContent, options, cb, true );
  } else {
    _returnArgsError( arguments );
  }
}

function fromUrl( url, options, cb ) {
  var urlNoQueryParams, extname, filePath, fullFilePath, file;

  if ( typeof url === 'string' ) {
    options = options || {};
    urlNoQueryParams = url.split( '?' )[0];
    extname = path.extname( urlNoQueryParams );
    filePath = _genRandom() + urlNoQueryParams.replace( /[^\w\s]/gi, '' ) + extname;
    fullFilePath = path.join( tmpDir, filePath );
    file = fs.createWriteStream( fullFilePath );
    file.on( 'finish', function() {
      fromFileWithPath( fullFilePath, options, cb );
    });

    got( url )
      .on( 'response', function( response ) {
        // allows for overriding by the developer or automatically
        // populating based on server response.
        if ( !options.typeOverride ) {
          options.typeOverride = response.headers['content-type'].split( /;/ )[0];
        }
      })
      .on ( 'error', typeof options === 'function' ? options : cb )
      .pipe( file );
  } else {
    _returnArgsError( arguments );
  }
}

module.exports = {
  fromFileWithPath: fromFileWithPath,
  fromFileWithMimeAndPath: fromFileWithMimeAndPath,
  fromBufferWithName: fromBufferWithName,
  fromBufferWithMime: fromBufferWithMime,
  fromUrl: fromUrl
};
<|endoftext|>


<commit_before>QUnit.module(
    "siblings()",
    {
        beforeEach: function ()
        {
            document.getElementById("qunit-fixture").innerHTML =
                '

' +
                '
'+
                    '

' +
                '
' +
                'Some text' +
                '

';
        }
    }
);

QUnit.test(
    "siblings() with an element in the middle",
    function (assert)
    {
        const siblings = mojave.dom.traverse.siblings;
        const element = document.querySelector(".test-element-find.element2");

        const result = siblings(element);

        assert.equal(result.length, 2, "found 2 elements");
        assert.ok(result[0].classList.contains("element1"), "contains .element1");
        assert.ok(result[0].classList.contains("element3"), "contains .element3");
    }
);

QUnit.test(
    "siblings() with an element at the start",
    function (assert)
    {
        const siblings = mojave.dom.traverse.siblings;
        const element = document.querySelector(".test-element-find.element1");

        const result = siblings(element);

        assert.equal(result.length, 2, "found 2 elements");
        assert.ok(result[0].classList.contains("element2"), "contains .element2");
        assert.ok(result[0].classList.contains("element3"), "contains .element3");
    }
);

QUnit.test(
    "siblings() with an element at the end",
    function (assert)
    {
        const siblings = mojave.dom.traverse.siblings;
        const element = document.querySelector(".test-element-find.element3");

        const result = siblings(element);

        assert.equal(result.length, 2, "found 2 elements");
        assert.ok(result[0].classList.contains("element1"), "contains .element1");
        assert.ok(result[0].classList.contains("element2"), "contains .element2");
    }
);

QUnit.test(
    "siblings() with an element without siblings",
    function (assert)
    {
        const siblings = mojave.dom.traverse.siblings;
        const element = document.querySelector(".test-element-find.element2-1");

        const result = siblings(element);

        assert.equal(result.length, 0, "found no elements");
    }
);
<commit_msg>Fix tests of siblings()<commit_after>QUnit.module(
    "siblings()",
    {
        beforeEach: function ()
        {
            document.getElementById("qunit-fixture").innerHTML =
                '

' +
                '
'+
                    '

' +
                '
' +
                'Some text' +
                '

';
        }
    }
);

QUnit.test(
    "siblings() with an element in the middle",
    function (assert)
    {
        const siblings = mojave.dom.traverse.siblings;
        const element = document.querySelector(".test-element-find.element2");

        const result = siblings(element);

        assert.equal(result.length, 2, "found 2 elements");
        assert.ok(result[0].classList.contains("element1"), "contains .element1");
        assert.ok(result[1].classList.contains("element3"), "contains .element3");
    }
);

QUnit.test(
    "siblings() with an element at the start",
    function (assert)
    {
        const siblings = mojave.dom.traverse.siblings;
        const element = document.querySelector(".test-element-find.element1");

        const result = siblings(element);

        assert.equal(result.length, 2, "found 2 elements");
        assert.ok(result[0].classList.contains("element2"), "contains .element2");
        assert.ok(result[1].classList.contains("element3"), "contains .element3");
    }
);

QUnit.test(
    "siblings() with an element at the end",
    function (assert)
    {
        const siblings = mojave.dom.traverse.siblings;
        const element = document.querySelector(".test-element-find.element3");

        const result = siblings(element);

        assert.equal(result.length, 2, "found 2 elements");
        assert.ok(result[0].classList.contains("element1"), "contains .element1");
        assert.ok(result[1].classList.contains("element2"), "contains .element2");
    }
);

QUnit.test(
    "siblings() with an element without siblings",
    function (assert)
    {
        const siblings = mojave.dom.traverse.siblings;
        const element = document.querySelector(".test-element-find.element2-1");

        const result = siblings(element);

        assert.equal(result.length, 0, "found no elements");
    }
);
<|endoftext|>


<commit_before>var container = $('.slides');
var isRetina = true;
// TODO: Translations
//
// var baseUrl = 'http://quran.com/quran/ajax?s=2&sA=1&eA=12&json=0';
// Format: json.verses[11][6].ayah.text -- 11 is ayah id, 6 is translation id...
//
// do this with response:
// for(var x in json.verses){
//   console.log(json.verses[x][6].ayah.text);
// }

var getVerseImageURL = function(surah, verse){
  var baseUrl = isRetina ? "http://quran.com/images/ayat_retina/" : "http://c00022506.cdn1.cloudfiles.rackspacecloud.com/";
  return baseUrl+surah+"_"+verse+".png";
}

var createNewSlide = function(surah, verse){
  var html = "

"+surah+":"+verse+"

";
  $(container).append(html)
}

var createSlideSequence = function(surah, startVerse, endVerse){
  for (var i = startVerse; i <= endVerse; i++) {
    createNewSlide(surah, i);
  }
}

var paseVersesRequest = function(request){
  //Take off the first hash
  var requestArray = request.substring(1).split(':');

  // The following string is either a number or a hiphenation of 2 numbers (eg 4-5)
  var verseRequest = requestArray[1] != undefined ? requestArray[1].split('-') : [];
  var verseRequestType = verseRequest.length === 1 ? 'verse' : verseRequest.length === 2 ? 'range' : 'error';

  return {
    surah: parseInt(requestArray[0]), // The first number is the surah number
    type: verseRequestType,
    startVerse: parseInt(verseRequest[0]),
    endVerse: parseInt(verseRequest[1])
  }

}

var doReveal = function(){
  // Full list of configuration options available here:
  // https://github.com/hakimel/reveal.js#configuration
  Reveal.initialize({
    controls: false,
    progress: true,
    history: false,
    center: true,

    theme: Reveal.getQueryHash().theme, // available themes are in /css/theme
    transition: Reveal.getQueryHash().transition || 'fade', // default/cube/page/concave/zoom/linear/fade/none

    // Optional libraries used to extend on reveal.js
    dependencies: [
      { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
      { src: 'plugin/markdown/showdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
      { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
      { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
      { src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
      { src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
      // { src: 'plugin/remotes/remotes.js', async: true, condition: function() { return !!document.body.classList; } }
    ]
  });
}

$(document).ready(function(){
  var verseRequest = paseVersesRequest(window.location.search);
  console.log(verseRequest);
  var doRange = false;
  var doVerse = false;
  var doSurah = verseRequest.surah !== NaN;
  if(doSurah && verseRequest.type != 'error'){
    doRange = (verseRequest.type == 'range' && verseRequest.startVerse != NaN && verseRequest.endVerse != NaN);
    doVerse = (verseRequest.type == 'verse' && verseRequest.startVerse != NaN);
    if(doSurah && doRange){
      createSlideSequence(verseRequest.surah, verseRequest.startVerse, verseRequest.endVerse);
      doReveal(); // Start presentation
    } else if(doSurah && doVerse && !doRange){
      createNewSlide(verseRequest.surah, verseRequest.startVerse);
      doReveal(); // Start presentation
    }
  } else {
    if(doSurah){
      alert('Surah-only requests coming soon');
    }
    alert("Please add a request to your url, e.g. "+window.location.origin+window.location.host+window.location.pathname+"?1:1");
  }

});<commit_msg>isRetina now implemented.<commit_after>var root = (typeof exports == 'undefined' ? window : exports);
var container = $('.slides');
var isRetina = (root.devicePixelRatio > 1) || (root.matchMedia && root.matchMedia("(-webkit-min-device-pixel-ratio: 1.5),(min--moz-device-pixel-ratio: 1.5),(-o-min-device-pixel-ratio: 3/2),(min-resolution: 1.5dppx)").matches);
// TODO: Translations
//
// var baseUrl = 'http://quran.com/quran/ajax?s=2&sA=1&eA=12&json=0';
// Format: json.verses[11][6].ayah.text -- 11 is ayah id, 6 is translation id...
//
// do this with response:
// for(var x in json.verses){
//   console.log(json.verses[x][6].ayah.text);
// }

var getVerseImageURL = function(surah, verse){
  var baseUrl = isRetina ? "http://quran.com/images/ayat_retina/" : "http://c00022506.cdn1.cloudfiles.rackspacecloud.com/";
  return baseUrl+surah+"_"+verse+".png";
}

var createNewSlide = function(surah, verse){
  var html = "

"+surah+":"+verse+"

";
  $(container).append(html)
}

var createSlideSequence = function(surah, startVerse, endVerse){
  for (var i = startVerse; i <= endVerse; i++) {
    createNewSlide(surah, i);
  }
}

var paseVersesRequest = function(request){
  //Take off the first hash
  var requestArray = request.substring(1).split(':');

  // The following string is either a number or a hiphenation of 2 numbers (eg 4-5)
  var verseRequest = requestArray[1] != undefined ? requestArray[1].split('-') : [];
  var verseRequestType = verseRequest.length === 1 ? 'verse' : verseRequest.length === 2 ? 'range' : 'error';

  return {
    surah: parseInt(requestArray[0]), // The first number is the surah number
    type: verseRequestType,
    startVerse: parseInt(verseRequest[0]),
    endVerse: parseInt(verseRequest[1])
  }

}

var doReveal = function(){
  // Full list of configuration options available here:
  // https://github.com/hakimel/reveal.js#configuration
  Reveal.initialize({
    controls: false,
    progress: true,
    history: false,
    center: true,

    theme: Reveal.getQueryHash().theme, // available themes are in /css/theme
    transition: Reveal.getQueryHash().transition || 'fade', // default/cube/page/concave/zoom/linear/fade/none

    // Optional libraries used to extend on reveal.js
    dependencies: [
      { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
      { src: 'plugin/markdown/showdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
      { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
      { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
      { src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
      { src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
      // { src: 'plugin/remotes/remotes.js', async: true, condition: function() { return !!document.body.classList; } }
    ]
  });
}

$(document).ready(function(){
  var verseRequest = paseVersesRequest(window.location.search);
  console.log(verseRequest);
  var doRange = false;
  var doVerse = false;
  var doSurah = verseRequest.surah !== NaN;
  if(doSurah && verseRequest.type != 'error'){
    doRange = (verseRequest.type == 'range' && verseRequest.startVerse != NaN && verseRequest.endVerse != NaN);
    doVerse = (verseRequest.type == 'verse' && verseRequest.startVerse != NaN);
    if(doSurah && doRange){
      createSlideSequence(verseRequest.surah, verseRequest.startVerse, verseRequest.endVerse);
      doReveal(); // Start presentation
    } else if(doSurah && doVerse && !doRange){
      createNewSlide(verseRequest.surah, verseRequest.startVerse);
      doReveal(); // Start presentation
    }
  } else {
    if(doSurah){
      alert('Surah-only requests coming soon');
    }
    alert("Please add a request to your url, e.g. "+window.location.origin+window.location.host+window.location.pathname+"?1:1");
  }

});<|endoftext|>


<commit_before>var gulp = require('gulp');
var fs = require('fs');
var exec = require('child_process').exec;
var babel = require('gulp-babel');
var jspm = require('jspm');

gulp.task('build', function(callback){
    exec('tsc -p .', function(error, stdout, stderr) {
        if(stdout){ console.log(stdout) }
        if(stderr){ console.log(stderr) }

        if(error){
            console.log('Typescript build error');
        }else{
            callback();
        }
   });
});

gulp.task('es5', ['build'], function() {
	return gulp.src('build/es6/**/*.js')
		.pipe(babel({
			presets: ['es2015']
		}))
		.pipe(gulp.dest('build/es5'));
})

gulp.task('bundle', ['es5'], function() {
	builder = new jspm.Builder();
	builder.config({
		paths: { '*': 'build/es5/*' }
	});

	let bundleSettings = {
		minify: true,
		mangle: false,
	}
	return Promise.all([
		builder.buildStatic('vendor/chrome/popup/bootstrap', 'build/merged/popup.min.js', bundleSettings),
		builder.buildStatic('vendor/chrome/background/main', 'build/merged/background.min.js', bundleSettings),
		builder.buildStatic('vendor/chrome/content/chrome', 'build/merged/content.min.js', bundleSettings),
		builder.buildStatic('vendor/chrome/options/options', 'build/merged/options.min.js', bundleSettings),
	]);
});

function fileCopy(src, dst) {
	return new Promise(resolve => gulp.src(src)
		.pipe(gulp.dest(dst))
		.on('end', resolve))
}

gulp.task('chrome-resources', ['es5'], function(){
	return Promise.all([
		fileCopy('vendor/chrome/**/*.html', 'dist/chrome/vendor/chrome'),
		fileCopy('vendor/chrome/resources/*', 'dist/chrome/resources'),
		fileCopy('vendor/chrome/manifest.json', 'dist/chrome'),
		fileCopy('config.js', 'dist/chrome'),
	]);
});

gulp.task('chrome-min-code', ['bundle'], function() {
	return Promise.all([
		fileCopy('build/merged/popup.min.js', 'dist/chrome/vendor/chrome/popup'),
		fileCopy('build/merged/background.min.js', 'dist/chrome/vendor/chrome/'),
		fileCopy('build/merged/content.min.js', 'dist/chrome/vendor/chrome/'),
		fileCopy('build/merged/options.min.js', 'dist/chrome/vendor/chrome/options'),
	])
});

gulp.task('default', ['chrome-min-code', 'chrome-resources']);
<commit_msg>Fixed diacritics<commit_after>var gulp = require('gulp');
var fs = require('fs');
var exec = require('child_process').exec;
var babel = require('gulp-babel');
var jspm = require('jspm');

gulp.task('build', function(callback){
    exec('tsc -p .', function(error, stdout, stderr) {
        if(stdout){ console.log(stdout) }
        if(stderr){ console.log(stderr) }

        if(error){
            console.log('Typescript build error');
        }else{
            callback();
        }
   });
});

gulp.task('es5', ['build'], function() {
	return gulp.src('build/es6/**/*.js')
		.pipe(babel({
			presets: ['es2015']
		}))
		.pipe(gulp.dest('build/es5'));
})

gulp.task('bundle', ['es5'], function() {
	builder = new jspm.Builder();
	builder.config({
		paths: { '*': 'build/es5/*' }
	});

	let bundleSettings = {
		minify: true,
		mangle: false, // terribleCache is truly terrible and uses constructor function names, which can't work if mangled
		uglify: {beautify: {ascii_only: true}}, // diacritics needs to faithfully store the unicode string map.
	}
	return Promise.all([
		builder.buildStatic('vendor/chrome/popup/bootstrap', 'build/merged/popup.min.js', bundleSettings),
		builder.buildStatic('vendor/chrome/background/main', 'build/merged/background.min.js', bundleSettings),
		builder.buildStatic('vendor/chrome/content/chrome', 'build/merged/content.min.js', bundleSettings),
		builder.buildStatic('vendor/chrome/options/options', 'build/merged/options.min.js', bundleSettings),
	]);
});

function fileCopy(src, dst) {
	return new Promise(resolve => gulp.src(src)
		.pipe(gulp.dest(dst))
		.on('end', resolve))
}

gulp.task('chrome-resources', ['es5'], function(){
	return Promise.all([
		fileCopy('vendor/chrome/**/*.html', 'dist/chrome/vendor/chrome'),
		fileCopy('vendor/chrome/resources/*', 'dist/chrome/resources'),
		fileCopy('vendor/chrome/manifest.json', 'dist/chrome'),
		fileCopy('config.js', 'dist/chrome'),
	]);
});

gulp.task('chrome-min-code', ['bundle'], function() {
	return Promise.all([
		fileCopy('build/merged/popup.min.js', 'dist/chrome/vendor/chrome/popup'),
		fileCopy('build/merged/background.min.js', 'dist/chrome/vendor/chrome/'),
		fileCopy('build/merged/content.min.js', 'dist/chrome/vendor/chrome/'),
		fileCopy('build/merged/options.min.js', 'dist/chrome/vendor/chrome/options'),
	])
});

gulp.task('default', ['chrome-min-code', 'chrome-resources']);
<|endoftext|>


<commit_before>var path = require("path"),
  extend = require("extend"),
  http = require("http"),
  io = require('socket.io'),
  util = require('util'),
  UglifyJS = require("uglify-js"),
  debug = require("debug")("myelements:server"),
  ElementsEventHandler = require("./elements-event-handler"),
  sharedSession = require("express-socket.io-session"),
  clientVersion = require('../package').version;

var config = {
  socketNamespace: "/myelements",
  session: undefined
};

module.exports = Server;
/**
 * Attachs a myelements handler to an express app (for emiting events on client
 * connection) and an http/https server for receiving client side events.
 * @param {express.App} app. An express request handler (express app)
 * @param {http.Server} httpServer. An http/https server to attach socket.io
 * @param {Object} options.
 *   - {String} socketNamespace: . Default `/myelements`
 *   - {Function} session: an express session middleware as the one returned
       by require("express-session")({...});
 */
function Server(app, httpServer, options) {
  if (!(this instanceof Server)) {
    return new Server(app, httpServer, options);
  }
  config = extend({}, config, options);
  this.attach = attach;
  this.serveClient = serveClientOnExpressRoute;
  this.attach(app, httpServer);
}
/**
 * @param {express.App}
 * @param {http.Server}
 */
function attach(app, httpServer) {
  //Attach routes for browser client library
  if (app.use === undefined) {
    throw new Error("Unknown express() object passed to myelements. Please pass an " +
      "an express app (request handler function)");
  }
  if (!(httpServer instanceof http.Server)) {
    throw new Error("Unknown server object passed to myelements. Please pass an " +
      "http.Server as second parameters");
  }
  serveClientOnExpressRoute(app);
  attachToHttpServer(httpServer, function onClientConnection(err, elementsEventHandler) {
    app.emit("myelements client connected", elementsEventHandler);
  });
}

/**
 * Listen for socket.io events on httpServer.
 *
 * @param {http.Server} httpServer. The server to attach socket.io to.
 * @param {Function} onConnectionCallback. Called when a socket client connects.
 *   - @param {Error} err. Null if nothing bad happened.
 *   - @param {EventEmitter} client. Event client.
 */
function attachToHttpServer(httpServer, onConnectionCallback) {
  // socket.io

  var sockets = io.listen(httpServer);
  debug("Attaching to http.Server");
  attachToSocketIo(sockets, onConnectionCallback);

}

/**
 * @param {io.Server} sockets
 */
function attachToSocketIo(sockets, onConnectionCallback) {
  // Communicate with client via myelements namespace
  var namespacedSockets = sockets.of(config.socketNamespace);
  // User express-session function passed as options
  // to myelements
  if (config.session) {
    debug("Using express session");

    namespacedSockets.use(sharedSession(config.session));
  }
  debug("Listening for socket.io client connections on namespace %s",
    config.socketNamespace);
  namespacedSockets.on('connection', function onSocketConnection(clientSocket) {
    onClientConnection(clientSocket, onConnectionCallback)
  });
}

function onClientConnection(clientSocket, onConnectionCallback) {

  var elementsEventHandler = new ElementsEventHandler(clientSocket);
  elementsEventHandler.session = clientSocket.handshake.session;
  debug("myelements client connected");

  onConnectionCallback(null, elementsEventHandler);
  elementsEventHandler.on("disconnect", function deleteElementsEventHandler() {
    delete elementsEventHandler;
  });
}

/**
 * Defines the route /events/client.js and serves up the browser javascript code
 * The client depends on jQuery and socket.io client being already loaded
 * @param {Express}
 */
function serveClientOnExpressRoute(app) {
  var join = path.join;
  var sources = [
    require.resolve('socket.io-client/socket.io.js'),
    join(__dirname, "client", "lib/ejs/ejs_0.9_alpha_1_production.js"),
    join(__dirname, "client", "lib/page.js/page.js"),
    join(__dirname, "client", "lib/localforage/localforage.js"),
    join(__dirname, "client", "lib/debug/debug.js"),
    join(__dirname, "client", "lib/jquery.ui.widget/jquery.ui.widget.js"),
    join(__dirname, "client", "myelements.jquery.js")
  ];
  app.get("/myelements.jquery.js", function(req, res, next) {
    res.setHeader("Content-type", "application/javascript");
    var result = UglifyJS.minify(sources, {
      mangle: false,
      compress: false
    });
    res.send(result.code);
    //res.sendFile(path.join(__dirname, "client.js"));
  });
}
<commit_msg>added incline doc for function signature. Added commented code for reporting etag based client code version (ala socket.io)<commit_after>var path = require("path"),
  extend = require("extend"),
  http = require("http"),
  io = require('socket.io'),
  UglifyJS = require("uglify-js"),
  debug = require("debug")("myelements:server"),
  ElementsEventHandler = require("./elements-event-handler"),
  sharedSession = require("express-socket.io-session"),
  clientVersion = require('../package').version;

var config = {
  // Default socket.io namespaced used by myelements
  socketNamespace: "/myelements",
  // Use no session middleware by default.
  session: undefined
};

module.exports = Server;
/**
 * Attachs a myelements handler to an express app (for emiting events on client
 * connection) and an http/https server for receiving client side events.
 * @param {express.App} app. An express request handler (express app)
 * @param {http.Server} httpServer. An http/https server to attach socket.io
 * @param {Object} options.
 *   - {String} socketNamespace: . Default `/myelements`
 *   - {Function} session: an express session middleware as the one returned
       by require("express-session")({...});
 */
function Server(app, httpServer, options) {
  if (!(this instanceof Server)) {
    return new Server(app, httpServer, options);
  }
  config = extend({}, config, options);
  this.attach = attach;
  this.serveClient = serveClientOnExpressRoute;
  this.attach(app, httpServer);
}
/**
 * @param {express.App}
 * @param {http.Server}
 */
function attach(app, httpServer) {
  //Attach routes for browser client library
  if (app.use === undefined) {
    throw new Error("Unknown express() object passed to myelements. Please pass an " +
      "an express app (request handler function)");
  }
  if (!(httpServer instanceof http.Server)) {
    throw new Error("Unknown server object passed to myelements. Please pass an " +
      "http.Server as second parameters");
  }
  serveClientOnExpressRoute(app);
  attachToHttpServer(httpServer, function onClientConnection(err, elementsEventHandler) {
    app.emit("myelements client connected", elementsEventHandler);
  });
}

/**
 * Listen for socket.io events on httpServer.
 *
 * @param {http.Server} httpServer. The server to attach socket.io to.
 * @param {Function} onConnectionCallback. Called when a socket client connects.
 *   - @param {Error} err. Null if nothing bad happened.
 *   - @param {EventEmitter} client. Event client.
 */
function attachToHttpServer(httpServer, onConnectionCallback) {
  // socket.io

  var sockets = io.listen(httpServer);
  debug("Attaching to http.Server");
  attachToSocketIo(sockets, onConnectionCallback);

}

/**
 * @param {io.Server} sockets
 */
function attachToSocketIo(sockets, onConnectionCallback) {
  // Communicate with client via myelements namespace
  var namespacedSockets = sockets.of(config.socketNamespace);
  // User express-session function passed as options
  // to myelements
  if (config.session) {
    debug("Using express session");

    namespacedSockets.use(sharedSession(config.session));
  }
  debug("Listening for socket.io client connections on namespace %s",
    config.socketNamespace);
  namespacedSockets.on('connection', function onSocketConnection(clientSocket) {
    onClientConnection(clientSocket, onConnectionCallback);
  });
}
/**
 * Handles a new myelements client connection.
 *
 * @param {socket}. client socket for the new connection
 * @param {Function} onConnectionCallback. called after socket.io connection event
 *   - @param {Error} err. Null if nothing bad happened.
 *   - @param {ElementsEventHandler} elementsEventHandler. An instance
 *     of myelements client's event handler.
 */
function onClientConnection(clientSocket, onConnectionCallback) {

  var elementsEventHandler = new ElementsEventHandler(clientSocket);
  elementsEventHandler.session = clientSocket.handshake.session;
  debug("myelements client connected");

  onConnectionCallback(null, elementsEventHandler);
  elementsEventHandler.on("disconnect", function deleteElementsEventHandler() {
    elementsEventHandler = undefined;
  });
}

/**
 * Defines the route /events/client.js and serves up the browser javascript code
 *
 * The client depends on jQuery and socket.io client being already loaded
 * @param {express.App} app. An express request handler.
 */
function serveClientOnExpressRoute(app) {
  var join = path.join;
  var sources = [
    require.resolve('socket.io-client/socket.io.js'),
    join(__dirname, "client", "lib/ejs/ejs_0.9_alpha_1_production.js"),
    join(__dirname, "client", "lib/page.js/page.js"),
    join(__dirname, "client", "lib/localforage/localforage.js"),
    join(__dirname, "client", "lib/debug/debug.js"),
    join(__dirname, "client", "lib/jquery.ui.widget/jquery.ui.widget.js"),
    join(__dirname, "client", "myelements.jquery.js")
  ];
  app.get("/myelements.jquery.js", function(req, res) {
    //logic taken form socket.io's serveClient
    // var etag = req.headers['if-none-match'];
    // if (etag) {
    //   if (clientVersion == etag) {
    //     debug('serve client 304');
    //     res.writeHead(304);
    //     res.end();
    //     return;
    //   }
    // }
    // debug('serve client source');
    // res.setHeader('ETag', clientVersion);
    res.setHeader("Content-type", "application/javascript");
    var result = UglifyJS.minify(sources, {
      mangle: false,
      compress: false
    });
    res.send(result.code);
    //res.sendFile(path.join(__dirname, "client.js"));
  });
}<|endoftext|>


<commit_before>var kindOf = require('./kindOf')

function isObject (value) {
  return kindOf(value) === 'object'
}

module.exports = isObject
<commit_msg>update lang/isObject<commit_after>function isObject (value) {
  return Object.prototype.toString.call(value) === '[object Object]'
}

module.exports = isObject
<|endoftext|>


<commit_before>/**
 * Created by gillbeits on 01/04/15.
 */

var
  HOST        = 'http://fontello.com',

  crypto      = require('crypto'),
  needle      = require('needle'),
  through2    = require('through2'),
  AdmZip      = require('adm-zip'),
  path        = require('path'),
  $           = require('gulp-util'),
  yargs       = require('yargs'),
  extend      = require('util')._extend,

  PluginError = $.PluginError
  ;

const PLUGIN_NAME = 'gulp-fontello';

function fontello (opts) {
  "use strict";

  opts = extend({
    assetsOnly: true,
    host: HOST
  }, extend(opts || {}, yargs.argv));

  return through2.obj(function (file, enc, callback) {
    var self = this;

    var process = function (zipContents, callback) {
      var
        zip = new AdmZip(zipContents),
        zipEntries = zip.getEntries()
        ;

      zipEntries.forEach(function (zipEntry) {
        var dirName, fileName, pathName, _ref;

        if (zipEntry.isDirectory) return;

        pathName = zipEntry.entryName;
        dirName = (_ref = path.dirname(pathName).match(/\/([^\/]*)$/)) != null ? _ref[1] : void 0;
        fileName = path.basename(pathName);

        if (opts.assetsOnly && !dirName) return;

        var content = zipEntry.getData();
        if (opts['font'] && opts['font'] != 'font' && path.extname(fileName) == '.css') {
          content = new Buffer(String(content).replace(new RegExp('\.\.\/font\/', 'g'), '../' + opts['font'] + '/'));
        }

        var file = new $.File({
          cwd: "./",
          path: (dirName ? ((opts[dirName] ? opts[dirName] : dirName) + '/') : '') + fileName,
          contents: content
        });
        self.push(file);
      });

      callback();
    };

    var fetchFromHost = function (callback) {
      var stream = through2.obj(function (file) {
        if (!file.toString()) {
          throw new PluginError(PLUGIN_NAME, "No session at Fontello for zip archive");
        }

        needle.get(opts.host + "/" + file.toString() + "/get", function (error, response) {
          if (error) {
            throw error;
          }

          // store in cache if configured
          if (opts.cache) {
            opts.cache.set(configHash, response.body);
          }

          process(response.body, callback);
        });
      });

      needle.post(opts.host, {
        config: {
          buffer: file.contents,
          filename: 'fontello.json',
          content_type: 'application/json'
        }
      }, {multipart: true}).pipe(stream);
    };

    // create SHA256 of the contents of the config file
    var configHash = crypto.createHash('sha256').update(file.contents).digest('hex');

    // use cache if configured
    if (opts.cache) {
      // check cache first
      opts.cache.get(configHash, function (error, cachedResponseBody) {
        // on cache err or empty response use normal fetch
        if (error || !cachedResponseBody) {
          fetchFromHost(callback);
        } else {
          $.log('using cached fontello zip for config with sha1: ' + configHash);
          process(cachedResponseBody, callback);
        }
      });
    } else {
      fetchFromHost(callback);
    }
  });
}

module.exports = fontello;
<commit_msg>add simple file-system based cache that can be used<commit_after>/**
 * Created by gillbeits on 01/04/15.
 */

var
  HOST        = 'http://fontello.com',

  fs          = require('fs'),
  crypto      = require('crypto'),
  needle      = require('needle'),
  through2    = require('through2'),
  AdmZip      = require('adm-zip'),
  path        = require('path'),
  $           = require('gulp-util'),
  yargs       = require('yargs'),
  extend      = require('util')._extend,

  PluginError = $.PluginError
  ;

const PLUGIN_NAME = 'gulp-fontello';

function fontello (opts) {
  "use strict";

  opts = extend({
    assetsOnly: true,
    host: HOST
  }, extend(opts || {}, yargs.argv));

  return through2.obj(function (file, enc, callback) {
    var self = this;

    var process = function (zipContents, callback) {
      var
        zip = new AdmZip(zipContents),
        zipEntries = zip.getEntries()
        ;

      zipEntries.forEach(function (zipEntry) {
        var dirName, fileName, pathName, _ref;

        if (zipEntry.isDirectory) return;

        pathName = zipEntry.entryName;
        dirName = (_ref = path.dirname(pathName).match(/\/([^\/]*)$/)) != null ? _ref[1] : void 0;
        fileName = path.basename(pathName);

        if (opts.assetsOnly && !dirName) return;

        var content = zipEntry.getData();
        if (opts['font'] && opts['font'] != 'font' && path.extname(fileName) == '.css') {
          content = new Buffer(String(content).replace(new RegExp('\.\.\/font\/', 'g'), '../' + opts['font'] + '/'));
        }

        var file = new $.File({
          cwd: "./",
          path: (dirName ? ((opts[dirName] ? opts[dirName] : dirName) + '/') : '') + fileName,
          contents: content
        });
        self.push(file);
      });

      callback();
    };

    var fetchFromHost = function (callback) {
      var stream = through2.obj(function (file) {
        if (!file.toString()) {
          throw new PluginError(PLUGIN_NAME, "No session at Fontello for zip archive");
        }

        needle.get(opts.host + "/" + file.toString() + "/get", function (error, response) {
          if (error) {
            throw error;
          }

          // store in cache if configured
          if (opts.cache) {
            opts.cache.set(configHash, response.body);
          }

          process(response.body, callback);
        });
      });

      needle.post(opts.host, {
        config: {
          buffer: file.contents,
          filename: 'fontello.json',
          content_type: 'application/json'
        }
      }, {multipart: true}).pipe(stream);
    };

    // create SHA256 of the contents of the config file
    var configHash = crypto.createHash('sha256').update(file.contents).digest('hex');

    // use cache if configured
    if (opts.cache) {
      // check cache first
      opts.cache.get(configHash, function (error, cachedResponseBody) {
        // on cache err or empty response use normal fetch
        if (error || !cachedResponseBody) {
          fetchFromHost(callback);
        } else {
          $.log('using cached fontello zip for config with sha1: ' + configHash);
          process(cachedResponseBody, callback);
        }
      });
    } else {
      fetchFromHost(callback);
    }
  });
}

/**
 * simple file-system based cache
 *
 * @param cacheDir
 * @returns {{get: 'get', set: 'set'}}
 */
fontello.simpleFsCache = function(cacheDir) {
  if (!fs.lstatSync(cacheDir).isDirectory()) {
    fs.mkdirSync(cacheDir);
  }

  return {
    'get': function(file, cb) {
      fs.readFile(path.join(cacheDir, file + ".cached.zip"), function(err, result) {
        if (err || !result) {
          cb();
        } else {
          cb(null, result);
        }
      });
    },
    'set': function(file, response) {
      fs.writeFile(path.join(cacheDir, file + ".cached.zip"), response, function noop() {});
    }
  }
};

module.exports = fontello;
<|endoftext|>


<commit_before>Upload = (awsBucketName, options) {
  this.aws = null; // initial aws connection

  this.awsBucketName = awsBucketName;

  // Set default options
  this.path = options.path || '/images';
  this.url = options.url || null;
  this.sizes = options.sizes || [780, 320];
  this.keepOriginal = options.keepOriginal || true; // @TODO this won't work

  return this;
}

Upload.prototype._resize = () {
  // resize image
  throw new Error('Not implemeted');
}

Upload.prototype._upload = () {
  // upload to aws
  throw new Error('Not implemeted');
}

Upload.prototype.upload = (tmpFile, callback) {
  // this is the publicly accessible method
}
<commit_msg>Init S3 bucket on new class instance<commit_after>S3 = require('AWS').S3;

Upload = (awsBucketName, options) {
  this.s3 = new S3({ params: { Bucket: awsBucketName } });

  // Set options
  this.path = options.path || '/';
  this.url = options.url || null;
  this.sizes = options.sizes || [780, 320];
  this.keepOriginal = options.keepOriginal || true; // @TODO this won't work

  return this;
}

Upload.prototype._resize = () {
  // resize image
  throw new Error('Not implemeted');
}

Upload.prototype._upload = () {
  // upload to aws
  throw new Error('Not implemeted');
}

Upload.prototype.upload = (tmpFile, callback) {
  // this is the publicly accessible method
}
<|endoftext|>


<commit_before>/*
== BSD2 LICENSE ==
Copyright (c) 2014, Tidepool Project

This program is free software; you can redistribute it and/or modify it under
the terms of the associated License, which is identical to the BSD 2-Clause
License as published by the Open Source Initiative at opensource.org.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the License for more details.

You should have received a copy of the License along with this program; if
not, you can obtain one from Tidepool Project at tidepool.org.
== BSD2 LICENSE ==
*/

request = require('superagent');

module.exports = function(config,hostGetter) {

    function getAPIHost(){
        //we just want the first one in this instance
        var hostSpec = hostGetter.get();
        return hostSpec[0].host;
    }

    function checkToken(req, res, next) {

        var sessionToken = req.headers['x-tidepool-session-token'];

        request
            .get(getAPIHost()+'/token/'+req.params.usertoken)
            .set('X-Tidepool-Session-Token', sessionToken)
            .end(function(error,response){

                if (error != null) {
                    res.send(503);
                    return next(error);
                }

                if(response.status == 200){
                    //console.log('success for token check ',response.body.userid);
                    res.tidepool={};
                    res.tidepool.userid = response.body.userid;
                }else if(response.status ==401){
                    //console.log('no auth for token check');
                    res.send(401,'Tidepool user-api');
                }

                return next();
            });
    };

    function getToken(req, res, next) {

        if(req.headers['x-tidepool-session-token'] != null){
            //console.log('we all ready have a token');
            return next();
        }else{
            request
            .post(getAPIHost()+'/serverlogin')
            .set('X-Tidepool-Server-Name', config.serverName)
            .set('X-Tidepool-Server-Secret', config.serverSecret)
            .end(function(error,response){

                if (error != null) {
                    res.send(503);
                    return next(error);
                }

                if(response.status == 200){
                    //console.log('got a new token',response.headers['x-tidepool-session-token']);
                    req.header('x-tidepool-session-token', response.headers['x-tidepool-session-token']);
                }else if(response.status ==401){
                    res.send(401,'Tidepool user-api /serverlogin');
                }

                return next();
            });
        }
    };

    return {
        checkToken : checkToken,
        getToken : getToken
    };

}<commit_msg>use a switch and cleanup<commit_after>/*
== BSD2 LICENSE ==
Copyright (c) 2014, Tidepool Project

This program is free software; you can redistribute it and/or modify it under
the terms of the associated License, which is identical to the BSD 2-Clause
License as published by the Open Source Initiative at opensource.org.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the License for more details.

You should have received a copy of the License along with this program; if
not, you can obtain one from Tidepool Project at tidepool.org.
== BSD2 LICENSE ==
*/

request = require('superagent');

module.exports = function(config,hostGetter) {

    function getAPIHost(){
        //we just want the first one in this instance
        var hostSpec = hostGetter.get();
        return hostSpec[0].host;
    }

    function checkToken(req, res, next) {

        var sessionToken = req.headers['x-tidepool-session-token'];

        request
            .get(getAPIHost()+'/token/'+req.params.usertoken)
            .set('X-Tidepool-Session-Token', sessionToken)
            .end(function(error,response){

                if (error != null) {
                    res.send(503);
                    return next(error);
                }

                switch(response.status) {
                    case 200:
                        res.tidepool={};
                        res.tidepool.userid = response.body.userid;
                        break;
                    case 401:
                        res.send(401,'Tidepool user-api: '+response.body);
                        break;
                    default:
                        res.send(response.status,'Tidepool user-api: '+response.body);
                        break;
                }

                return next();
            });
    };

    function getToken(req, res, next) {

        if(req.headers['x-tidepool-session-token'] != null){
            //console.log('we all ready have a token');
            return next();
        }else{
            request
            .post(getAPIHost()+'/serverlogin')
            .set('X-Tidepool-Server-Name', config.serverName)
            .set('X-Tidepool-Server-Secret', config.serverSecret)
            .end(function(error,response){

                if (error != null) {
                    res.send(503);
                    return next(error);
                }

                switch(response.status) {
                    case 200:
                        req.header('x-tidepool-session-token', response.headers['x-tidepool-session-token']);
                        break;
                    case 401:
                        res.send(401,'Tidepool user-api: '+response.body);
                        break;
                    default:
                        res.send(response.status,'Tidepool user-api: '+response.body);
                        break;
                }

                return next();
            });
        }
    };

    return {
        checkToken : checkToken,
        getToken : getToken
    };

}<|endoftext|>


<commit_before>var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var exec = require('child_process').exec;
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var plumber = require('gulp-plumber');
var reload = browserSync.reload;
var rename = require('gulp-rename');
var sass = require('gulp-sass');
// var scsslint = require('gulp-scss-lint');
var stylish = require('jshint-stylish');

// Target these browsers for adding vendor prefixes to CSS
var BROWSERS = [
  "> 5%",
  "ie > 0",
  "Firefox > 0",
  "Chrome > 0",
  "Opera > 0",
  "OperaMobile > 0",
  "OperaMini > 0",
  "Safari > 0",
  "iOS > 0",
  "Blackberry > 0",
  "Android > 0"
];

// Initialize browser-sync and proxy web server
gulp.task('browser-sync', function() {
  browserSync.init({
    logPrefix: "Pattern Library",
    server: {
      baseDir: "./dev"
    }
  });
});

// Get the patterns ready for distribution
gulp.task('dist', function() {
  gulp.src(['dev/patterns/**/*.scss', 'dev/patterns/**/*.md'])
    .pipe(plumber())
    .pipe(gulp.dest('dist/patterns'));

  gulp.src('dev/*.scss')
    .pipe(plumber())
    .pipe(rename('_pattern-library.scss'))
    .pipe(gulp.dest('dist'));

  gulp.src('dev/images/*.png')
    .pipe(plumber())
    .pipe(gulp.dest('dist/images'));
});

// Lint JavaScript and JSON files.
gulp.task('jslint', function() {
  return gulp.src(['*.json', '*.js', 'dist/patterns/**/*.json'])
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

// Full Browser Reload (HTML, JS, JSON files)
gulp.task('reload', reload);

// Lint Sass files (.scss)
// gulp.task('scss-lint', function() {
//   gulp.src(['dev/*.scss', 'dev/patterns/**/*.scss'])
//     .pipe(scsslint());
// });

// Compile and prefix Sass code into CSS,
// then reload the browser (stream when possible).
gulp.task('sass', function() {
  gulp.src(['dev/*.scss', 'dev/patterns/**/*.scss'])
    .pipe(plumber())
    .pipe(sass())
    .pipe(autoprefixer({
      browsers: BROWSERS
    }))
    .pipe(gulp.dest('dev'))
    .pipe(browserSync.stream());
});

// Watch for changes on these files
// Run these specific tasks when files change.
gulp.task('watch', function() {
  gulp.watch(['dev/patterns/**/html/*.html', 'dev/patterns/*.html']).on('change', reload);
  gulp.watch(['*.json', '*.js', 'dist/patterns/**/*.json', 'dev/patterns/*.js'], ['jslint']).on('change', reload);
  gulp.watch(['dev/*.scss', 'dev/patterns/**/*.scss'], ['sass', 'dist']);
  // If you have scss-lint:
  // gulp.watch(['dev/*.scss', 'dev/patterns/**/*.scss'], ['sass', 'scss-lint', 'dist']);
});

// Default task -- run these tasks.
gulp.task('default', ['browser-sync', 'sass', 'dist', 'watch']);
<commit_msg>Create dirs object, 'use strict' and comments<commit_after>'use-strict';

//////////////////////////////
// Requires
//////////////////////////////
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var exec = require('child_process').exec;
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var plumber = require('gulp-plumber');
var reload = browserSync.reload;
var rename = require('gulp-rename');
var sass = require('gulp-sass');
// var scsslint = require('gulp-scss-lint');
var stylish = require('jshint-stylish');

//////////////////////////////
// Variables
//////////////////////////////

// Autoprefixer:
// Target these browsers for adding vendor prefixes to CSS
var BROWSERS = [
  "> 5%",
  "ie > 0",
  "Firefox > 0",
  "Chrome > 0",
  "Opera > 0",
  "OperaMobile > 0",
  "OperaMini > 0",
  "Safari > 0",
  "iOS > 0",
  "Blackberry > 0",
  "Android > 0"
];

var dirs = {
  'sass': 'dev/patterns/**/*.scss',
  'js': {
    'lint': [
      'Gulpfile.js',
      '*.json',
      'dev/dev.js',
      'dev/patterns/**/package.json'
    ]
  },
  'html': {
    'reload': [
      'dev/index.html',
      'dev/patterns/**/html/*.html'
    ]
  }
};

// Initialize browser-sync and proxy web server
gulp.task('browser-sync', function() {
  browserSync.init({
    logPrefix: "Pattern Library",
    server: {
      baseDir: "./dev"
    }
  });
});

// Get the patterns ready for distribution
gulp.task('dist', function() {
  gulp.src(['dev/patterns/**/*.scss', 'dev/patterns/**/*.md'])
    .pipe(plumber())
    .pipe(gulp.dest('dist/patterns'));

  gulp.src('dev/*.scss')
    .pipe(plumber())
    .pipe(rename('_pattern-library.scss'))
    .pipe(gulp.dest('dist'));

  gulp.src('dev/images/*.png')
    .pipe(plumber())
    .pipe(gulp.dest('dist/images'));
});

// Lint JavaScript and JSON files.
gulp.task('jslint', function() {
  return gulp.src(['*.json', '*.js', 'dist/patterns/**/*.json'])
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

// Full Browser Reload (HTML, JS, JSON files)
gulp.task('reload', reload);

// Lint Sass files (.scss)
// gulp.task('scss-lint', function() {
//   gulp.src(['dev/*.scss', 'dev/patterns/**/*.scss'])
//     .pipe(scsslint());
// });

// Compile and prefix Sass code into CSS,
// then reload the browser (stream when possible).
gulp.task('sass', function() {
  gulp.src(['dev/*.scss', 'dev/patterns/**/*.scss'])
    .pipe(plumber())
    .pipe(sass())
    .pipe(autoprefixer({
      browsers: BROWSERS
    }))
    .pipe(gulp.dest('dev'))
    .pipe(browserSync.stream());
});

// Watch for changes on these files
// Run these specific tasks when files change.
gulp.task('watch', function() {
  gulp.watch(['dev/patterns/**/html/*.html', 'dev/patterns/*.html']).on('change', reload);
  gulp.watch(['*.json', '*.js', 'dist/patterns/**/*.json', 'dev/patterns/*.js'], ['jslint']).on('change', reload);
  gulp.watch(['dev/*.scss', 'dev/patterns/**/*.scss'], ['sass', 'dist']);
  // If you have scss-lint:
  // gulp.watch(['dev/*.scss', 'dev/patterns/**/*.scss'], ['sass', 'scss-lint', 'dist']);
});

// Default task -- run these tasks.
gulp.task('default', ['browser-sync', 'sass', 'dist', 'watch']);
<|endoftext|>