<commit_before>import Webiny from 'Webiny';
import LinkState from './LinkState';
import Dispatcher from './Dispatcher';
import UiDispatcher from './UiDispatcher';

class Component extends React.Component {

    constructor(props) {
        super(props);

        this.__listeners = [];
        this.__cursors = [];
        this.bindMethods('bindTo,isRendered');
    }

    componentWillMount() {
        if (this.props.ui) {
            UiDispatcher.register(this.props.ui, this);
        }
    }

    componentDidMount() {
        // Reserved for future system-wide functionality
    }

    /* eslint-disable */
    componentWillReceiveProps(nextProps) {
        if (nextProps.ui != this.props.ui) {
            UiDispatcher.unregister(this.props.ui);
            UiDispatcher.register(nextProps.ui, this);
        }
    }

    shouldComponentUpdate(nextProps, nextState) {
        // Reserved for future system-wide functionality
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
        // Reserved for future system-wide functionality
    }

    componentDidUpdate(prevProps, prevState) {
        // Reserved for future system-wide functionality
    }

    /* eslint-enable */

    componentWillUnmount() {
        // Release event listeners
        _.forEach(this.__listeners, unsubscribe => {
            unsubscribe();
        });
        this.__listeners = [];

        // Release data cursors
        _.forEach(this.__cursors, cursor => {
            if (cursor && cursor.tree) {
                cursor.release();
            }
        });
        this.__cursors = [];

        if (this.props.ui) {
            UiDispatcher.unregister(this.props.ui);
        }
    }

    setState(key, value = null, callback = null) {
        if (_.isObject(key)) {
            return super.setState(key, value);
        }

        if (_.isString(key)) {
            const state = this.state;
            _.set(state, key, value);
            return super.setState(state, callback);
        }
    }

    isRendered() {
        if (_.has(this.props, 'renderIf')) {
            return _.isFunction(this.props.renderIf) ? this.props.renderIf() : this.props.renderIf;
        }
        return true;
    }

    onRouteChanged(callback) {
        const stopListening = Dispatcher.on('RouteChanged', callback);
        this.__listeners.push(stopListening);
    }

    getClassName() {
        return Object.getPrototypeOf(this).constructor.name;
    }

    isMobile() {
        return isMobile.any;
    }

    dispatch(action, data) {
        return Dispatcher.dispatch(action, data);
    }

    on(event, callback, meta) {
        const stopListening = Dispatcher.on(event, callback, meta);
        this.__listeners.push(stopListening);
    }

    classSet(...sets) {
        let classes = [];

        _.forIn(sets, classObject => {
            if (!classObject) {
                return;
            }

            if (typeof classObject === 'string') {
                classes = classes.concat(classObject.split(' '));
                return;
            }

            if (classObject instanceof Array) {
                classes = classes.concat(classObject);
                return;
            }

            _.forIn(classObject, (value, className) => {
                if (!value) {
                    return;
                }
                classes.push(className);
            });
        });

        return classes.join(' ');
    }

    /**
     * Ex: onChangeImportant(newValue, oldValue){...}
     * Ex: onChangeName(newValue, oldValue){...}
     *
     * @param key
     * @param callback
     * @param defaultValue
     * @returns {{value: *, requestChange: *}}
     */
    bindTo(key, callback = _.noop, defaultValue = null) {
        const ls = new LinkState(this, key, callback, _.clone(defaultValue));
        return ls.create();
    }

    bindMethods(...methods) {
        if (methods.length === 1 && _.isString(methods[0])) {
            methods = methods[0].split(',').map(x => x.trim());
        }

        _.forEach(methods, (name) => {
            if (name in this) {
                this[name] = this[name].bind(this);
            } else {
                console.info('Missing method [' + name + ']', this);
            }
        });
    }

    ui(call, ...params) {
        if (call.indexOf(':') < 0) {
            return UiDispatcher.get(call);
        }
        return UiDispatcher.createSignal(this, call, params);
    }

    watch(key, func) {
        const cursor = Webiny.Model.select(key.split('.'));
        cursor.on('update', e => {
            func(e.data.currentData, e.data.previousData, e);
        });
        this.__cursors.push(cursor);
        // Execute callback with initial data
        func(cursor.get());
        return cursor;
    }

    apiParams(params) {
        // TODO: need a simple Injector (like current Registry)
        // TODO: Things like `apiParams` will be constructed using a form in UI builder
        // TODO: values like '@activeLocation' will be dynamic, and are accessed through injector
        // TODO: Modules responsible for these values should make these values available to injector on module initialization
        const injected = {};
        _.each(params, (v, k) => {
            if (_.isPlainObject(v)) {
                injected[k] = this.apiParams(v);
                return;
            }

            if (_.isString(v) && v.startsWith('@')) {
                const parts = v.split(':');
                if (parts[0] === '@router') {
                    v = Webiny.Router.getParams(parts[1]);
                }
            }
            injected[k] = v;
        });
        return injected;
    }

    /**
     * Method for a more convenient use of i18n module - this will automatically generate a complete namespace for the label
     * If this method is called without parameters, it will return Webiny.i18n module, from which you can use other functions as well
     * @param label
     * @param variables
     * @param options
     * @returns {*}
     */
    i18n(label, variables, options = {}) {
        if (!label) {
            return Webiny.i18n;
        }

        const module = _.get(Webiny.Router.getActiveRoute(), 'module.name');
        const app = _.get(Webiny.Router.getActiveRoute(), 'module.app.name');
        const key = `${app}.${module}.${this.getClassName()}.${md5(label)}`;
        return <webiny-i18n id={key}>{Webiny.i18n(key, label, variables, options)}</webiny-i18n>;
    }

    render() {
        if (!this.isRendered()) {
            return null;
        }

        if (this.props.renderer) {
            try {
                // Here we prepare renderer parameters in case any were attached to the function itself using `bindArgs`
                let params = [this];
                if (this.props.renderer.bindArgs) {
                    params = params.concat(this.props.renderer.bindArgs);
                }
                params.push(this);
                return this.props.renderer.call(...params);
            } catch (e) {
                Webiny.Logger.reportError('js', e.message, e.stack);
                console.error('[RENDER ERROR][' + this.getClassName() + ']', e);
                return (

[RENDER ERROR] in component `{this.getClassName()}`

{e.stack}

                );
            }
        }

        console.warn('Component ' + this.getClassName() + ' has no renderer!');
        return null;
    }
}

export default Component;
<commit_msg>In production, component render errors will be hidden.<commit_after>import Webiny from 'Webiny';
import LinkState from './LinkState';
import Dispatcher from './Dispatcher';
import UiDispatcher from './UiDispatcher';

class Component extends React.Component {

    constructor(props) {
        super(props);

        this.__listeners = [];
        this.__cursors = [];
        this.bindMethods('bindTo,isRendered');
    }

    componentWillMount() {
        if (this.props.ui) {
            UiDispatcher.register(this.props.ui, this);
        }
    }

    componentDidMount() {
        // Reserved for future system-wide functionality
    }

    /* eslint-disable */
    componentWillReceiveProps(nextProps) {
        if (nextProps.ui != this.props.ui) {
            UiDispatcher.unregister(this.props.ui);
            UiDispatcher.register(nextProps.ui, this);
        }
    }

    shouldComponentUpdate(nextProps, nextState) {
        // Reserved for future system-wide functionality
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
        // Reserved for future system-wide functionality
    }

    componentDidUpdate(prevProps, prevState) {
        // Reserved for future system-wide functionality
    }

    /* eslint-enable */

    componentWillUnmount() {
        // Release event listeners
        _.forEach(this.__listeners, unsubscribe => {
            unsubscribe();
        });
        this.__listeners = [];

        // Release data cursors
        _.forEach(this.__cursors, cursor => {
            if (cursor && cursor.tree) {
                cursor.release();
            }
        });
        this.__cursors = [];

        if (this.props.ui) {
            UiDispatcher.unregister(this.props.ui);
        }
    }

    setState(key, value = null, callback = null) {
        if (_.isObject(key)) {
            return super.setState(key, value);
        }

        if (_.isString(key)) {
            const state = this.state;
            _.set(state, key, value);
            return super.setState(state, callback);
        }
    }

    isRendered() {
        if (_.has(this.props, 'renderIf')) {
            return _.isFunction(this.props.renderIf) ? this.props.renderIf() : this.props.renderIf;
        }
        return true;
    }

    onRouteChanged(callback) {
        const stopListening = Dispatcher.on('RouteChanged', callback);
        this.__listeners.push(stopListening);
    }

    getClassName() {
        return Object.getPrototypeOf(this).constructor.name;
    }

    isMobile() {
        return isMobile.any;
    }

    dispatch(action, data) {
        return Dispatcher.dispatch(action, data);
    }

    on(event, callback, meta) {
        const stopListening = Dispatcher.on(event, callback, meta);
        this.__listeners.push(stopListening);
    }

    classSet(...sets) {
        let classes = [];

        _.forIn(sets, classObject => {
            if (!classObject) {
                return;
            }

            if (typeof classObject === 'string') {
                classes = classes.concat(classObject.split(' '));
                return;
            }

            if (classObject instanceof Array) {
                classes = classes.concat(classObject);
                return;
            }

            _.forIn(classObject, (value, className) => {
                if (!value) {
                    return;
                }
                classes.push(className);
            });
        });

        return classes.join(' ');
    }

    /**
     * Ex: onChangeImportant(newValue, oldValue){...}
     * Ex: onChangeName(newValue, oldValue){...}
     *
     * @param key
     * @param callback
     * @param defaultValue
     * @returns {{value: *, requestChange: *}}
     */
    bindTo(key, callback = _.noop, defaultValue = null) {
        const ls = new LinkState(this, key, callback, _.clone(defaultValue));
        return ls.create();
    }

    bindMethods(...methods) {
        if (methods.length === 1 && _.isString(methods[0])) {
            methods = methods[0].split(',').map(x => x.trim());
        }

        _.forEach(methods, (name) => {
            if (name in this) {
                this[name] = this[name].bind(this);
            } else {
                console.info('Missing method [' + name + ']', this);
            }
        });
    }

    ui(call, ...params) {
        if (call.indexOf(':') < 0) {
            return UiDispatcher.get(call);
        }
        return UiDispatcher.createSignal(this, call, params);
    }

    watch(key, func) {
        const cursor = Webiny.Model.select(key.split('.'));
        cursor.on('update', e => {
            func(e.data.currentData, e.data.previousData, e);
        });
        this.__cursors.push(cursor);
        // Execute callback with initial data
        func(cursor.get());
        return cursor;
    }

    apiParams(params) {
        // TODO: need a simple Injector (like current Registry)
        // TODO: Things like `apiParams` will be constructed using a form in UI builder
        // TODO: values like '@activeLocation' will be dynamic, and are accessed through injector
        // TODO: Modules responsible for these values should make these values available to injector on module initialization
        const injected = {};
        _.each(params, (v, k) => {
            if (_.isPlainObject(v)) {
                injected[k] = this.apiParams(v);
                return;
            }

            if (_.isString(v) && v.startsWith('@')) {
                const parts = v.split(':');
                if (parts[0] === '@router') {
                    v = Webiny.Router.getParams(parts[1]);
                }
            }
            injected[k] = v;
        });
        return injected;
    }

    /**
     * Method for a more convenient use of i18n module - this will automatically generate a complete namespace for the label
     * If this method is called without parameters, it will return Webiny.i18n module, from which you can use other functions as well
     * @param label
     * @param variables
     * @param options
     * @returns {*}
     */
    i18n(label, variables, options = {}) {
        if (!label) {
            return Webiny.i18n;
        }

        const module = _.get(Webiny.Router.getActiveRoute(), 'module.name');
        const app = _.get(Webiny.Router.getActiveRoute(), 'module.app.name');
        const key = `${app}.${module}.${this.getClassName()}.${md5(label)}`;
        return <webiny-i18n id={key}>{Webiny.i18n(key, label, variables, options)}</webiny-i18n>;
    }

    render() {
        if (!this.isRendered()) {
            return null;
        }

        if (this.props.renderer) {
            try {
                // Here we prepare renderer parameters in case any were attached to the function itself using `bindArgs`
                let params = [this];
                if (this.props.renderer.bindArgs) {
                    params = params.concat(this.props.renderer.bindArgs);
                }
                params.push(this);
                return this.props.renderer.call(...params);
            } catch (e) {
                if (webinyEnvironment === 'production') {
                    return null;
                }
                Webiny.Logger.reportError('js', e.message, e.stack);
                console.error('[RENDER ERROR][' + this.getClassName() + ']', e);
                return (

[RENDER ERROR] in component `{this.getClassName()}`

{e.stack}

                );
            }
        }

        console.warn('Component ' + this.getClassName() + ' has no renderer!');
        return null;
    }
}

export default Component;
<|endoftext|>


<commit_before>/* test/site_routes_test.js -- test Site routes
 * Copyright 2014 Sergei Ianovich
 *
 * Licensed under AGPL-3.0 or later, see LICENSE
 * Process Control Service Web Interface
 */

var expect = require('expect.js');
var Routes = require('../routes/site');

var siteAttrs = {
  name: "Some site",
};

describe('Site routes', function() {
  var site;
  before(function(done) {
    Factory.create('site', function (s) { site = s; done(); });
  });

  describe("#load", function() {
    it("should find by id and assign site to req", function(done) {
      var req = { },
      id = site._id;

      Routes.load(req, {}, function() {
        expect(req.site.toJSON()).to.eql(site.toJSON());
        done();
      }, id);
    });

    it("should respond with not found code", function(done) {
      var res = {
        send: function(code) {
          expect(code).to.eql(404);
          done();
        }
      };
      Routes.load({}, res, null, 0);
    });
  });
});

// vim:ts=2 sts=2 sw=2 et:

<commit_msg>tests: routes: deprecate access unauthorized users for site<commit_after>/* test/site_routes_test.js -- test Site routes
 * Copyright 2014 Sergei Ianovich
 *
 * Licensed under AGPL-3.0 or later, see LICENSE
 * Process Control Service Web Interface
 */

var expect = require('expect.js');
var Routes = require('../routes/site');
var router = require('./support/router');

var siteAttrs = {
  name: "Some site",
};

describe('Site routes', function() {
  var site;
  before(function(done) {
    Factory.create('site', function (s) { site = s; done(); });
  });

  describe("#load", function() {
    it("should find by id and assign site to req", function(done) {
      var req = { },
      id = site._id;

      Routes.load(req, {}, function() {
        expect(req.site.toJSON()).to.eql(site.toJSON());
        done();
      }, id);
    });

    it("should respond with not found code", function(done) {
      var res = {
        send: function(code) {
          expect(code).to.eql(404);
          done();
        }
      };
      Routes.load({}, res, null, 0);
    });
  });

  describe("#show", function() {
    it("should deny access to non-signed-in users", function(done) {
      var req = { session: {} },
      res = { redirect: function(url) {
        expect(url).to.eql("/signin");
        done();
      }};
      router(Routes.show, req, res);
    });
  });
});

// vim:ts=2 sts=2 sw=2 et:

<|endoftext|>


<commit_before>/*!
 * B - Benchmarks for Node.js.
 *
 * Veselin Todorov <hi@vesln.com>
 * MIT License.
 */

/**
 * Benchmark constructor.
 *
 * Examples:
 *
 *
 *
 * @param {String} name [optional]
 * @param {Object} writable stream [optional]
 * @param {Function} functionality to benchmark [optional]
 */
function Benchmark(name, stream, cb) {
  if ('function' === typeof stream || null === stream) {
    cb = stream;
    stream = process.stdout;
  }
  this.name = name;
  this.stream = stream;
  this.cb = cb;
  this._start = null;
  this._end = null;
  this._time = null;
};

/**
 * Runs the benchmark. Usually used with when testing
 * asynchronous code.
 *
 * @returns `this`
 * @api public
 */
Benchmark.prototype.run = function() {
  var self = this;
  var done = function() {
    self.end().done();
  };
  this.start().cb(done);
};

/**
 * Called when a benchmark is done.
 *
 * @api public
 */
Benchmark.prototype.done = function() {
  this.time = this._end - this._start;
  this.print();
  return this;
};

/**
 * Prints the results from the benchmark.
 *
 * @returns `this`
 * @api private
 */
Benchmark.prototype.print = function() {
  var out = '';
  if (this.name) out += this.name + ' ';
  out += this.time + 'ms';
  this.stream.write(out);
  return this;
};

/**
 * Starts the timer.
 *
 * @returns `this`
 * @api public
 */
Benchmark.prototype.start = function(name) {
  this._start = Date.now();
  return this;
};

/**
 * Stops the timer.
 *
 * @returns `this`
 * @api public
 */
Benchmark.prototype.end = function() {
  this._end = Date.now();

  // If benchmarking syncrhonous code calls done and otuputs the results.
  if ('function' !== typeof this.cb) {
    return this.done();
  }

  return this;
};

/**
 * Expose `Benchmark`.
 */
module.exports = Benchmark;<commit_msg>Misc.<commit_after>/*!
 * B - Benchmarks for Node.js.
 *
 * Veselin Todorov <hi@vesln.com>
 * MIT License.
 */

/**
 * Benchmark constructor.
 *
 * Examples:
 *
 *
 *
 * @param {String} name [optional]
 * @param {Object} writable stream [optional]
 * @param {Function} functionality to benchmark [optional]
 */
function Benchmark(name, stream, cb) {
  if ('function' === typeof stream || null === stream) {
    cb = stream;
    stream = process.stdout;
  }
  this.name = name;
  this.stream = stream;
  this.cb = cb;
  this._start = null;
  this._end = null;
  this._time = null;
};

/**
 * Runs the benchmark. Usually used with when testing
 * asynchronous code.
 *
 * @returns `this`
 * @api public
 */
Benchmark.prototype.run = function() {
  var self = this;
  var done = function() {
    self.end().done();
  };
  this.start().cb(done);
};

/**
 * Called when a benchmark is done.
 *
 * @api public
 */
Benchmark.prototype.done = function() {
  this.time = this._end - this._start;
  this.print();
  return this;
};

/**
 * Prints the results from the benchmark.
 *
 * @returns `this`
 * @api private
 */
Benchmark.prototype.print = function() {
  var out = '';
  if (this.name) out += this.name + ' ';
  out += this.time + 'ms';
  this.stream.write(out);
  return this;
};

/**
 * Starts the timer.
 *
 * @returns `this`
 * @api public
 */
Benchmark.prototype.start = function(name) {
  this._start = Date.now();
  return this;
};

/**
 * Stops the timer.
 *
 * @returns `this`
 * @api public
 */
Benchmark.prototype.end = function() {
  this._end = Date.now();

  // If benchmarking syncrhonous code calls done and otuputs the results.
  if ('function' !== typeof this.cb) return this.done();

  return this;
};

/**
 * Expose `Benchmark`.
 */
module.exports = Benchmark;<|endoftext|>


<commit_before>'use strict'

const fs = require('fs')
const path = require('path')
const express = require('express')
const jade = require('jade')
const util = require('./util')
const rootPath = path.join(__dirname, '/../../..')

class CleverPackage {

  constructor (cleverCoreInstance, name) {
    this.cleverCoreInstance = cleverCoreInstance

    this.loadedPackage = cleverCoreInstance.pkgList.packageNamed(name)

    this.waiters = []

    if (!this.loadedPackage) {
      throw new Error(`Package with name ${name} is not loaded`)
    }

    this.name = this.loadedPackage.name.toLowerCase()

    this.viewsPath = `${rootPath}/app/packages/${this.name}/views`
    this.assetsPath = `${rootPath}/app/packages/${this.name}/assets/dist`

    // Attach CleverCore to pkg object
    this.CleverCore = this.cleverCoreInstance.getClass()

    // Router mounting  point
    this.mountPoint = null

    // Serve module assets folder
    this.cleverCoreInstance.resolve('app', app => {
      app.use(`/public/${this.name}`, express.static(this.assetsPath))
    })
  }

  render (view, opts) {
    return jade.renderFile(`${this.viewsPath}/${view}.jade`, opts)
  }

  attach (options) {
    if (options && options.where) {
      this.mountPoint = options.where
      return this
    }
    throw new Error('Attach method requires `option.where`')
  }

  routes (dependencies) {
    const pkgRoutesPath = this.loadedPackage.path('routes')

    const promise = new Promise((yep, nope) => {
      fs.exists(pkgRoutesPath, exists => {
        yep(exists)
      })
    })
    .then(exists => {
      if (!exists) return
      return new Promise((yep, nope) => {
        fs
          .readdir(this.loadedPackage.path('routes'), (err, files) => {
            if (err) return nope(err)
            yep(files)
          })
      })
    })
    .then(files => {
      return new Promise(done => {
        this.cleverCoreInstance.resolve('app', app => {
          done(app)
        })
      })
      .then(app => {
        const pkg = this
        return new Promise(done => {
          this.cleverCoreInstance.resolve(dependencies.concat(function () {
            const args = Array.prototype.slice.call(arguments)
            files.forEach(file => {
              app.use(pkg.mountPoint || `/${pkg.name}`,
                require(`${pkgRoutesPath}/${file}`).apply(null, [pkg].concat(args)))
            })
            done(pkg)
          }))
        })
      })
    })

    this.waiters.push(promise)
    return this
  }

  models () {
    const db = this.cleverCoreInstance.db
    const models = this.cleverCoreInstance.db.models
    const pkgModelsPath = `${rootPath}/app/packages/${this.name}/models`

    const promise = new Promise((yep, nope) => {
      fs
        .exists(pkgModelsPath, exists => {
          yep(exists)
        })
    })
    .then(exists => {
      if (!exists) return Promise.resolve()
      return new Promise((yep, nope) => {
        fs
          .readdir(pkgModelsPath, (err, files) => {
            if (err) return nope(err)
            yep(files)
          })
      })
      .then(files => {
        files.filter(file => {
          return (file.indexOf('.') !== 0) && (file !== 'index.js')
        })
        .forEach(file => {
          const model = db.import(path.join(pkgModelsPath, file))
          models[model.name] = model
        })
      })
    })

    this.waiters.push(promise)
    return this
  }

  register () {
    Promise
      .all(this.waiters)
      .then(() => {
        return this.cleverCoreInstance.register(this.name, this)
      })
      .catch(console.error.bind(console))
  }

  getCleverCore () {
    return this.CleverCore
  }

}

module.exports = CleverPackage
<commit_msg>Lint - Part 2<commit_after>'use strict'

const fs = require('fs')
const path = require('path')
const express = require('express')
const jade = require('jade')
const rootPath = path.join(__dirname, '/../../..')

class CleverPackage {

  constructor (cleverCoreInstance, name) {
    this.cleverCoreInstance = cleverCoreInstance

    this.loadedPackage = cleverCoreInstance.pkgList.packageNamed(name)

    this.waiters = []

    if (!this.loadedPackage) {
      throw new Error(`Package with name ${name} is not loaded`)
    }

    this.name = this.loadedPackage.name.toLowerCase()

    this.viewsPath = `${rootPath}/app/packages/${this.name}/views`
    this.assetsPath = `${rootPath}/app/packages/${this.name}/assets/dist`

    // Attach CleverCore to pkg object
    this.CleverCore = this.cleverCoreInstance.getClass()

    // Router mounting  point
    this.mountPoint = null

    // Serve module assets folder
    this.cleverCoreInstance.resolve('app', app => {
      app.use(`/public/${this.name}`, express.static(this.assetsPath))
    })
  }

  render (view, opts) {
    return jade.renderFile(`${this.viewsPath}/${view}.jade`, opts)
  }

  attach (options) {
    if (options && options.where) {
      this.mountPoint = options.where
      return this
    }
    throw new Error('Attach method requires `option.where`')
  }

  routes (dependencies) {
    const pkgRoutesPath = this.loadedPackage.path('routes')

    const promise = new Promise((yep, nope) => {
      fs.exists(pkgRoutesPath, exists => {
        yep(exists)
      })
    })
    .then(exists => {
      if (!exists) return
      return new Promise((yep, nope) => {
        fs
          .readdir(this.loadedPackage.path('routes'), (err, files) => {
            if (err) return nope(err)
            yep(files)
          })
      })
    })
    .then(files => {
      return new Promise(done => {
        this.cleverCoreInstance.resolve('app', app => {
          done(app)
        })
      })
      .then(app => {
        const pkg = this
        return new Promise(done => {
          this.cleverCoreInstance.resolve(dependencies.concat(function () {
            const args = Array.prototype.slice.call(arguments)
            files.forEach(file => {
              app.use(pkg.mountPoint || `/${pkg.name}`,
                require(`${pkgRoutesPath}/${file}`).apply(null, [pkg].concat(args)))
            })
            done(pkg)
          }))
        })
      })
    })

    this.waiters.push(promise)
    return this
  }

  models () {
    const db = this.cleverCoreInstance.db
    const models = this.cleverCoreInstance.db.models
    const pkgModelsPath = `${rootPath}/app/packages/${this.name}/models`

    const promise = new Promise((yep, nope) => {
      fs
        .exists(pkgModelsPath, exists => {
          yep(exists)
        })
    })
    .then(exists => {
      if (!exists) return Promise.resolve()
      return new Promise((yep, nope) => {
        fs
          .readdir(pkgModelsPath, (err, files) => {
            if (err) return nope(err)
            yep(files)
          })
      })
      .then(files => {
        files.filter(file => {
          return (file.indexOf('.') !== 0) && (file !== 'index.js')
        })
        .forEach(file => {
          const model = db.import(path.join(pkgModelsPath, file))
          models[model.name] = model
        })
      })
    })

    this.waiters.push(promise)
    return this
  }

  register () {
    Promise
      .all(this.waiters)
      .then(() => {
        return this.cleverCoreInstance.register(this.name, this)
      })
      .catch(console.error.bind(console))
  }

  getCleverCore () {
    return this.CleverCore
  }

}

module.exports = CleverPackage
<|endoftext|>


<commit_before>/*
 *  d.js
 *
 *  David Janes
 *  IOTDB.org
 *  2014-02-14
 *  "Valentines's Day"
 *
 *  Dictionary functions
 *
 *  Copyright (2013-2020) David P. Janes
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

const _ = require("../helpers");

// NodeJS dependency loop workaround
if (!_.each) {
    _.each = require('lodash').each;
}

/**
 *  Slash-path oriented
 */
const get = function(keystored, key, otherwise) {
    if (!keystored) {
        return otherwise;
    }
    if (!key) {
        return otherwise;
    }

    let d = keystored;
    const subkeys = key.replace(/^\/*/, '').split('/');
    let lastkey = subkeys[subkeys.length - 1];

    for (let ski = 0; ski < subkeys.length - 1; ski++) {
        let subkey = subkeys[ski];
        let subd = d[subkey];

        while (_.is.Array(subd) && subd.length) {
            subd = subd[0]
        }

        if (subd === undefined) {
            return otherwise;
        } else if (_.is.Object(subd)) {
            d = subd;
        } else {
            return otherwise;
        }
    }

    let value = d[lastkey];
    if (value === undefined) {
        return otherwise;
    }

    return value;
};

/**
 */
const first = function(keystored, key, otherwise) {
    let value = get(keystored, key, undefined);
    if (value === undefined) {
        return otherwise;
    } else if (_.is.Array(value)) {
        if (value.length) {
            return value[0];
        } else {
            return otherwise;
        }
    } else {
        return value;
    }
};

/**
 */
const list = function(keystored, key, otherwise) {
    let value = get(keystored, key, undefined);
    if (value === undefined) {
        return otherwise;
    } else if (_.is.Array(value)) {
        return value;
    } else {
        return [ value ];
    }
};

/**
 *  Slash-path oriented
 */
const set = function(keystored, key, value) {
    let d = keystored;
    let subkeys = key.replace(/^\/*/, '').split('/');
    let lastkey = subkeys[subkeys.length - 1];

    for (let ski = 0; ski < subkeys.length - 1; ski++) {
        let subkey = subkeys[ski];
        let subd = d[subkey];
        if (!_.is.Object(subd)) {
            subd = {};
            d[subkey] = subd;
        }

        d = subd;
    }

    d[lastkey] = value;
};

/**
 *  Slash-path oriented
 */
const do_delete = function(keystored, key) {
    let d = keystored;
    let subkeys = key.replace(/^\/*/, '').split('/');
    let lastkey = subkeys[subkeys.length - 1];

    for (let ski = 0; ski < subkeys.length - 1; ski++) {
        let subkey = subkeys[ski];
        let subd = d[subkey];
        if (!_.is.Object(subd)) {
            return;
        }

        d = subd;
    }

    delete d[lastkey];
};

/*
 *  Apply a function to keys and values of a dictionary
 */
const transform = function(o, paramd) {
    paramd = _.defaults(paramd, {
        key: function(key, value, paramd) {
            return key;
        },
        value: function(value, paramd) {
            return value;
        },
        filter: function(value, paramd) {
            return (value !== undefined);
        },
        pre: function(value, paramd) {
            return value;
        },
        post: function(value, paramd) {
            return value;
        },
    });

    let _transform = function(v, paramd) {
        if (_.is.Array(v)) {
            let ovs = v;
            let nvs = [];
            for (let ovx in ovs) {
                let ov = ovs[ovx];
                let nv = _transform(ov, paramd);
                if (paramd.filter(nv)) {
                    nvs.push(nv);
                }
            }
            return nvs;
        } else if ((v !== null) && _.is.Date(v)) {
            return paramd.value(v, paramd);
        } else if ((v !== null) && _.is.Object(v)) {
            let ovd = paramd.pre(v, paramd);
            let nvd = {};
            for (let ovkey in ovd) {
                let ovvalue = ovd[ovkey];

                let nvkey = paramd.key(ovkey, ovvalue, paramd);
                if (!nvkey) {
                    continue;
                }

                let nparamd = _.d.clone.shallow(paramd);
                nparamd._key = nvkey;

                let nvvalue = _transform(ovvalue, nparamd);
                if (paramd.filter(nvvalue)) {
                    nvd[nvkey] = nvvalue;
                }
            }
            return nvd;
        } else {
            return paramd.value(v, paramd);
        }
    };

    o = paramd.pre(o, paramd);
    o = _transform(o, paramd);
    o = paramd.post(o, paramd);

    return o;
};

/**
 *  Return true iff everything in subd is in superd
 *  Note that not recursive on dictionaries
 */
const d_contains_d = function (superd, subd) {
    if (!_.is.Dictionary(superd)) {
        return false;
    }
    if (!_.is.Dictionary(subd)) {
        return false;
    }

    let subkeys = _.keys(subd);
    for (let sx in subkeys) {
        let subkey = subkeys[sx];
        let subvalue = subd[subkey];
        let supervalue = superd[subkey];
        if (!_.is.Equal(subvalue, supervalue)) {
            return false;
        }
    }

    return true;
};

/**
 *  Returns a JSON-scrubed version
 */
const json = function (xvalue) {
    if (xvalue === undefined) {
        return undefined;
    } else if (_.is.Function(xvalue)) {
        return undefined;
    } else if (_.is.NaN(xvalue)) {
        return undefined;
    } else if (_.is.Array(xvalue)) {
        let ns = [];
        xvalue.map(function(o) {
            let n = json(o);
            if (n !== undefined) {
                ns.push(n);
            }
        });
        return ns;
    } else if (_.is.Object(xvalue)) {
        let nd = {};
        _.mapObject(xvalue, function(o, key) {
            let n = json(o);
            if (n !== undefined) {
                nd[key] = n;
            }
        });
        return nd;
    } else {
        return xvalue;
    }
};

/**
 */
const to_underscore_case = xvalue => {
    if (_.is.Array(xvalue)) {
        return xvalue.map(o => to_underscore_case(o))
    } else if (_.is.Dictionary(xvalue)) {
        let nd = {}

        _.mapObject(xvalue, function(value, key) {
            nd[_.id.to_underscore_case(key, true)] = value
        })

        return nd
    } else {
        return xvalue
    }
}

/**
 *  Like compose, but will descend into dictionaries
 *  to merge those. The *first* thing seen always takes
 *  precidence in replacement
 */
const deep_compose = (...ods) => {
    const xd = {};

    ods
        .filter(od => _.is.Object(od))
        .forEach(od => {
            _.mapObject(od, ( y, key ) => {
                const x = xd[key];
                if (_.is.Dictionary(x) && _.is.Dictionary(y)) {
                    xd[key] = deep_compose(x, y);
                } else if (_.is.Null(x)) {
                    xd[key] = _.d.clone.deep(y);
                } else if (_.is.Undefined(x)) {
                    xd[key] = _.d.clone.deep(y);
                }
            });
        });

    return xd;
};

/**
 *  Return a new Object composed of all its
 *  arguments. A value is _only_ set if it's
 *  not already set from a preceeding argument.
 */
const shallow_compose = function () {
    let d = {};

    _.each(arguments, function (ad) {
        for (let key in ad) {
            if (d[key] === undefined) {
                d[key] = ad[key];
            }
        }
    });

    return d;
};

const shallow_clone = function (oldObj) {
    let newObj = {};
    for (let i in oldObj) {
        if (oldObj.hasOwnProperty(i)) {
            newObj[i] = oldObj[i];
        }
    }
    return newObj;
};

const deep_clone = function (oldObj) {
    let newObj = oldObj;
    if (oldObj && typeof oldObj === 'object') {
        newObj = Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
        for (let i in oldObj) {
            newObj[i] = deep_clone(oldObj[i]);
        }
    }
    return newObj;
};

const add = (d, key, value) => {
    d = shallow_clone(d);
    set(d, key, value);
    return d;
}

const update = (d, nd) => Object.assign({}, d, nd);

exports.d = {
    get: get,
    first: first,
    list: list,
    set: set,
    delete: do_delete,
    transform: transform,
    json: json,
    add: add,
    update: update,
    compose: shallow_compose,
    clone: shallow_clone,
    is: {
        superset: (a, b) => d_contains_d(a, b),
        subset: (a, b) => d_contains_d(b, a),
    }
};

exports.d.transform.json = json
exports.d.transform.underscore_case = to_underscore_case

exports.d.compose.shallow = shallow_compose;
exports.d.compose.deep = deep_compose;
exports.d.clone.shallow = shallow_clone;
exports.d.clone.deep = deep_clone;
<commit_msg>_.d.transform.denull<commit_after>/*
 *  d.js
 *
 *  David Janes
 *  IOTDB.org
 *  2014-02-14
 *  "Valentines's Day"
 *
 *  Dictionary functions
 *
 *  Copyright (2013-2020) David P. Janes
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

"use strict";

const _ = require("../helpers");

// NodeJS dependency loop workaround
if (!_.each) {
    _.each = require('lodash').each;
}

/**
 *  Slash-path oriented
 */
const get = function(keystored, key, otherwise) {
    if (!keystored) {
        return otherwise;
    }
    if (!key) {
        return otherwise;
    }

    let d = keystored;
    const subkeys = key.replace(/^\/*/, '').split('/');
    let lastkey = subkeys[subkeys.length - 1];

    for (let ski = 0; ski < subkeys.length - 1; ski++) {
        let subkey = subkeys[ski];
        let subd = d[subkey];

        while (_.is.Array(subd) && subd.length) {
            subd = subd[0]
        }

        if (subd === undefined) {
            return otherwise;
        } else if (_.is.Object(subd)) {
            d = subd;
        } else {
            return otherwise;
        }
    }

    let value = d[lastkey];
    if (value === undefined) {
        return otherwise;
    }

    return value;
};

/**
 */
const first = function(keystored, key, otherwise) {
    let value = get(keystored, key, undefined);
    if (value === undefined) {
        return otherwise;
    } else if (_.is.Array(value)) {
        if (value.length) {
            return value[0];
        } else {
            return otherwise;
        }
    } else {
        return value;
    }
};

/**
 */
const list = function(keystored, key, otherwise) {
    let value = get(keystored, key, undefined);
    if (value === undefined) {
        return otherwise;
    } else if (_.is.Array(value)) {
        return value;
    } else {
        return [ value ];
    }
};

/**
 *  Slash-path oriented
 */
const set = function(keystored, key, value) {
    let d = keystored;
    let subkeys = key.replace(/^\/*/, '').split('/');
    let lastkey = subkeys[subkeys.length - 1];

    for (let ski = 0; ski < subkeys.length - 1; ski++) {
        let subkey = subkeys[ski];
        let subd = d[subkey];
        if (!_.is.Object(subd)) {
            subd = {};
            d[subkey] = subd;
        }

        d = subd;
    }

    d[lastkey] = value;
};

/**
 *  Slash-path oriented
 */
const do_delete = function(keystored, key) {
    let d = keystored;
    let subkeys = key.replace(/^\/*/, '').split('/');
    let lastkey = subkeys[subkeys.length - 1];

    for (let ski = 0; ski < subkeys.length - 1; ski++) {
        let subkey = subkeys[ski];
        let subd = d[subkey];
        if (!_.is.Object(subd)) {
            return;
        }

        d = subd;
    }

    delete d[lastkey];
};

/*
 *  Apply a function to keys and values of a dictionary
 */
const transform = function(o, paramd) {
    paramd = _.defaults(paramd, {
        key: function(key, value, paramd) {
            return key;
        },
        value: function(value, paramd) {
            return value;
        },
        filter: function(value, paramd) {
            return (value !== undefined);
        },
        pre: function(value, paramd) {
            return value;
        },
        post: function(value, paramd) {
            return value;
        },
    });

    let _transform = function(v, paramd) {
        if (_.is.Array(v)) {
            let ovs = v;
            let nvs = [];
            for (let ovx in ovs) {
                let ov = ovs[ovx];
                let nv = _transform(ov, paramd);
                if (paramd.filter(nv)) {
                    nvs.push(nv);
                }
            }
            return nvs;
        } else if ((v !== null) && _.is.Date(v)) {
            return paramd.value(v, paramd);
        } else if ((v !== null) && _.is.Object(v)) {
            let ovd = paramd.pre(v, paramd);
            let nvd = {};
            for (let ovkey in ovd) {
                let ovvalue = ovd[ovkey];

                let nvkey = paramd.key(ovkey, ovvalue, paramd);
                if (!nvkey) {
                    continue;
                }

                let nparamd = _.d.clone.shallow(paramd);
                nparamd._key = nvkey;

                let nvvalue = _transform(ovvalue, nparamd);
                if (paramd.filter(nvvalue)) {
                    nvd[nvkey] = nvvalue;
                }
            }
            return nvd;
        } else {
            return paramd.value(v, paramd);
        }
    };

    o = paramd.pre(o, paramd);
    o = _transform(o, paramd);
    o = paramd.post(o, paramd);

    return o;
};

/**
 *  Return true iff everything in subd is in superd
 *  Note that not recursive on dictionaries
 */
const d_contains_d = function (superd, subd) {
    if (!_.is.Dictionary(superd)) {
        return false;
    }
    if (!_.is.Dictionary(subd)) {
        return false;
    }

    let subkeys = _.keys(subd);
    for (let sx in subkeys) {
        let subkey = subkeys[sx];
        let subvalue = subd[subkey];
        let supervalue = superd[subkey];
        if (!_.is.Equal(subvalue, supervalue)) {
            return false;
        }
    }

    return true;
};

/**
 *  Returns a JSON-scrubed version
 */
const to_json = function (xvalue) {
    if (xvalue === undefined) {
        return undefined;
    } else if (_.is.Function(xvalue)) {
        return undefined;
    } else if (_.is.NaN(xvalue)) {
        return undefined;
    } else if (_.is.Array(xvalue)) {
        let ns = [];
        xvalue.map(function(o) {
            let n = to_json(o);
            if (n !== undefined) {
                ns.push(n);
            }
        });
        return ns;
    } else if (_.is.Object(xvalue)) {
        let nd = {};
        _.mapObject(xvalue, function(o, key) {
            let n = to_json(o);
            if (n !== undefined) {
                nd[key] = n;
            }
        });
        return nd;
    } else {
        return xvalue;
    }
};

/**
 *  Remove all nulls and undefined
 */
const to_denull = o => {
    if (_.is.Dictionary(o)) {
        const no = {}
        _.mapObject(o, (sv, sk) => {
            if (!_.is.Nullish(sv)) {
                no[sk] = to_denull(sv)
            }
        })

        return no
    } else if (_.is.Array(o)) {
        return o.filter(so => !_.is.Nullish(so)).map(to_denull)
    } else {
        return o
    }
}

/**
 */
const to_underscore_case = xvalue => {
    if (_.is.Array(xvalue)) {
        return xvalue.map(o => to_underscore_case(o))
    } else if (_.is.Dictionary(xvalue)) {
        let nd = {}

        _.mapObject(xvalue, function(value, key) {
            nd[_.id.to_underscore_case(key, true)] = value
        })

        return nd
    } else {
        return xvalue
    }
}

/**
 *  Like compose, but will descend into dictionaries
 *  to merge those. The *first* thing seen always takes
 *  precidence in replacement
 */
const deep_compose = (...ods) => {
    const xd = {};

    ods
        .filter(od => _.is.Object(od))
        .forEach(od => {
            _.mapObject(od, ( y, key ) => {
                const x = xd[key];
                if (_.is.Dictionary(x) && _.is.Dictionary(y)) {
                    xd[key] = deep_compose(x, y);
                } else if (_.is.Null(x)) {
                    xd[key] = _.d.clone.deep(y);
                } else if (_.is.Undefined(x)) {
                    xd[key] = _.d.clone.deep(y);
                }
            });
        });

    return xd;
};

/**
 *  Return a new Object composed of all its
 *  arguments. A value is _only_ set if it's
 *  not already set from a preceeding argument.
 */
const shallow_compose = function () {
    let d = {};

    _.each(arguments, function (ad) {
        for (let key in ad) {
            if (d[key] === undefined) {
                d[key] = ad[key];
            }
        }
    });

    return d;
};

const shallow_clone = function (oldObj) {
    let newObj = {};
    for (let i in oldObj) {
        if (oldObj.hasOwnProperty(i)) {
            newObj[i] = oldObj[i];
        }
    }
    return newObj;
};

const deep_clone = function (oldObj) {
    let newObj = oldObj;
    if (oldObj && typeof oldObj === 'object') {
        newObj = Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
        for (let i in oldObj) {
            newObj[i] = deep_clone(oldObj[i]);
        }
    }
    return newObj;
};

const add = (d, key, value) => {
    d = shallow_clone(d);
    set(d, key, value);
    return d;
}

const update = (d, nd) => Object.assign({}, d, nd);

exports.d = {
    get: get,
    first: first,
    list: list,
    set: set,
    delete: do_delete,
    transform: transform,
    json: to_json,
    add: add,
    update: update,
    compose: shallow_compose,
    clone: shallow_clone,
    is: {
        superset: (a, b) => d_contains_d(a, b),
        subset: (a, b) => d_contains_d(b, a),
    }
};

exports.d.transform.json = to_json
exports.d.transform.underscore_case = to_underscore_case
exports.d.transform.denull = to_denull

exports.d.compose.shallow = shallow_compose;
exports.d.compose.deep = deep_compose;
exports.d.clone.shallow = shallow_clone;
exports.d.clone.deep = deep_clone;
<|endoftext|>


<commit_before>/**
* Copyright 2011 Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var fs = require('fs');
var path = require('path');
var utils = require('./utils');

var CacheUtils = {};

function getSpacesFile(context) {
  return path.join(utils.azureDir(), "spaces." + context.subscription + ".json");
}

function getSitesFile(context) {
  return path.join(utils.azureDir(), "sites." + context.subscription + ".json");
}

function getCommitIdsFile(context) {
  return path.join(utils.azureDir(), "commitids." + context.subscription + ".json");
}

function readSpaces(context, cb) {
  var cacheFile = getSpacesFile(context);
  return path.exists(cacheFile, function (exists) {
    if (exists) {
      return fs.readFile(cacheFile, function (err, data) {
        return cb && cb(null, JSON.parse(data));
      });
    }
    return cb && cb(null, []);
  });
}

function saveSpaces(context, spaces, cb) {
  var cacheFile = getSpacesFile(context);
  return fs.writeFile(cacheFile, JSON.stringify(spaces), function (err) {
    cb && cb(err, spaces);
  });
}

function readSite(context, cb) {
  var cacheFile = getSitesFile(context);
  return path.exists(cacheFile, function (exists) {
    if (exists) {
      return fs.readFile(cacheFile, function (err, data) {
        var sites = JSON.parse(data);
        if (sites && sites.length) {
          for (var i = 0; i < sites.length; i++) {
            if (utils.ignoreCaseEquals(context.site.name, sites[i].Name)) {
              return cb && cb(null, sites[i]);
            }
          }
        }
        return cb && cb(null, null);
      });
    }
    return cb && cb(null, null);
  });
}

function saveSite(context, site, cb) {
  var cacheFile = getSitesFile(context);
  return path.exists(cacheFile, function (exists) {
    if (exists) {
      return fs.readFile(cacheFile, function (err, data) {
        var sites = JSON.parse(data);
        if (sites && sites.length) {
          for (var i = 0; i < sites.length; i++) {
            if (utils.ignoreCaseEquals(site.Name, sites[i].Name)) {
              sites[i] = site;
              return saveSites(context, sites, cb);
            }
          }
          sites.push(site);
          return saveSites(context, sites, cb);
        }
        return saveSites(context, [site], cb);
      });
    }
    return saveSites(context, [site], cb);
  });
}

function deleteSite(context, cb) {
  var cacheFile = getSitesFile(context);
  return path.exists(cacheFile, function (exists) {
    if (exists) {
      return fs.readFile(cacheFile, function (err, data) {
        var sites = JSON.parse(data);
        if (sites && sites.length) {
          for (var i = 0; i < sites.length; i++) {
            if (utils.ignoreCaseEquals(context.site.name, sites[i].Name)) {
              sites.splice(i, 1);
              return saveSites(context, sites, cb);
            }
          }
        }
        return cb && cb(null, null);
      });
    }
    return cb && cb(null, null);
  });
}

function saveSites(context, sites, cb) {
  var cacheFile = getSitesFile(context);
  return fs.writeFile(cacheFile, JSON.stringify(sites), function (err) {
    cb && cb(err, sites);
  });
}

function saveCommitIds(context, deployments, cb) {
  var cacheFile = getCommitIdsFile(context);
  var commitIds = deployments.map(function (deployment) {
    return {
      shortId: deployment.shortId,
      id: deployment.id
    };
  });
  return fs.writeFile(cacheFile, JSON.stringify(commitIds), function (err) {
    cb && cb(err, deployments);
  });
}

function readCommitId(context, cb) {
  var cacheFile = getCommitIdsFile(context);
  return path.exists(cacheFile, function (exists) {
    if (exists) {
      return fs.readFile(cacheFile, function (err, data) {
        var commitIds = JSON.parse(data);
        if (commitIds && commitIds.length) {
          for (var i = 0; i < commitIds.length; i++) {
            if (utils.ignoreCaseEquals(context.shortId, commitIds[i].shortId)) {
              return cb && cb(null, commitIds[i].id);
            }
          }
        }
        return cb && cb(null, null);
      });
    }
    return cb && cb(null, null);
  });
}

function clear() {
  var isDeleted = false;
  if (path.existsSync(utils.azureDir())) {
    var cacheFiles = fs.readdirSync(utils.azureDir());
    for (var i = 0; i < cacheFiles.length; ++i) {
      if (/sites[.].+[.]json/.test(cacheFiles[i])
      || /spaces[.].+[.]json/.test(cacheFiles[i])
      || /commitids[.].+[.]json/.test(cacheFiles[i])) {
        fs.unlinkSync(path.join(utils.azureDir(), cacheFiles[i]));
        isDeleted = true;
      }
    }
  }
  return isDeleted;
};

CacheUtils.readSpaces = readSpaces;
CacheUtils.saveSpaces = saveSpaces;
CacheUtils.readSite = readSite;
CacheUtils.saveSite = saveSite;
CacheUtils.deleteSite = deleteSite;
CacheUtils.saveSites = saveSites;
CacheUtils.saveCommitIds = saveCommitIds;
CacheUtils.readCommitId = readCommitId;
CacheUtils.clear = clear;

module.exports = CacheUtils;<commit_msg>add support for deployment long id<commit_after>/**
* Copyright 2011 Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var fs = require('fs');
var path = require('path');
var utils = require('./utils');

var CacheUtils = {};

function getSpacesFile(context) {
  return path.join(utils.azureDir(), "spaces." + context.subscription + ".json");
}

function getSitesFile(context) {
  return path.join(utils.azureDir(), "sites." + context.subscription + ".json");
}

function getCommitIdsFile(context) {
  return path.join(utils.azureDir(), "commitids." + context.subscription + ".json");
}

function readSpaces(context, cb) {
  var cacheFile = getSpacesFile(context);
  return path.exists(cacheFile, function (exists) {
    if (exists) {
      return fs.readFile(cacheFile, function (err, data) {
        return cb && cb(null, JSON.parse(data));
      });
    }
    return cb && cb(null, []);
  });
}

function saveSpaces(context, spaces, cb) {
  var cacheFile = getSpacesFile(context);
  return fs.writeFile(cacheFile, JSON.stringify(spaces), function (err) {
    cb && cb(err, spaces);
  });
}

function readSite(context, cb) {
  var cacheFile = getSitesFile(context);
  return path.exists(cacheFile, function (exists) {
    if (exists) {
      return fs.readFile(cacheFile, function (err, data) {
        var sites = JSON.parse(data);
        if (sites && sites.length) {
          for (var i = 0; i < sites.length; i++) {
            if (utils.ignoreCaseEquals(context.site.name, sites[i].Name)) {
              return cb && cb(null, sites[i]);
            }
          }
        }
        return cb && cb(null, null);
      });
    }
    return cb && cb(null, null);
  });
}

function saveSite(context, site, cb) {
  var cacheFile = getSitesFile(context);
  return path.exists(cacheFile, function (exists) {
    if (exists) {
      return fs.readFile(cacheFile, function (err, data) {
        var sites = JSON.parse(data);
        if (sites && sites.length) {
          for (var i = 0; i < sites.length; i++) {
            if (utils.ignoreCaseEquals(site.Name, sites[i].Name)) {
              sites[i] = site;
              return saveSites(context, sites, cb);
            }
          }
          sites.push(site);
          return saveSites(context, sites, cb);
        }
        return saveSites(context, [site], cb);
      });
    }
    return saveSites(context, [site], cb);
  });
}

function deleteSite(context, cb) {
  var cacheFile = getSitesFile(context);
  return path.exists(cacheFile, function (exists) {
    if (exists) {
      return fs.readFile(cacheFile, function (err, data) {
        var sites = JSON.parse(data);
        if (sites && sites.length) {
          for (var i = 0; i < sites.length; i++) {
            if (utils.ignoreCaseEquals(context.site.name, sites[i].Name)) {
              sites.splice(i, 1);
              return saveSites(context, sites, cb);
            }
          }
        }
        return cb && cb(null, null);
      });
    }
    return cb && cb(null, null);
  });
}

function saveSites(context, sites, cb) {
  var cacheFile = getSitesFile(context);
  return fs.writeFile(cacheFile, JSON.stringify(sites), function (err) {
    cb && cb(err, sites);
  });
}

function saveCommitIds(context, deployments, cb) {
  var cacheFile = getCommitIdsFile(context);
  var commitIds = deployments.map(function (deployment) {
    return {
      shortId: deployment.shortId,
      id: deployment.id
    };
  });
  return fs.writeFile(cacheFile, JSON.stringify(commitIds), function (err) {
    cb && cb(err, deployments);
  });
}

function readCommitId(context, cb) {
  var cacheFile = getCommitIdsFile(context);
  return path.exists(cacheFile, function (exists) {
    if (exists) {
      return fs.readFile(cacheFile, function (err, data) {
        var commitIds = JSON.parse(data);
        if (commitIds && commitIds.length) {
          for (var i = 0; i < commitIds.length; i++) {
            if (utils.ignoreCaseEquals(context.shortId, commitIds[i].shortId)
              || utils.ignoreCaseEquals(context.shortId, commitIds[i].id)) {
              return cb && cb(null, commitIds[i].id);
            }
          }
        }
        return cb && cb(null, null);
      });
    }
    return cb && cb(null, null);
  });
}

function clear() {
  var isDeleted = false;
  if (path.existsSync(utils.azureDir())) {
    var cacheFiles = fs.readdirSync(utils.azureDir());
    for (var i = 0; i < cacheFiles.length; ++i) {
      if (/sites[.].+[.]json/.test(cacheFiles[i])
      || /spaces[.].+[.]json/.test(cacheFiles[i])
      || /commitids[.].+[.]json/.test(cacheFiles[i])) {
        fs.unlinkSync(path.join(utils.azureDir(), cacheFiles[i]));
        isDeleted = true;
      }
    }
  }
  return isDeleted;
};

CacheUtils.readSpaces = readSpaces;
CacheUtils.saveSpaces = saveSpaces;
CacheUtils.readSite = readSite;
CacheUtils.saveSite = saveSite;
CacheUtils.deleteSite = deleteSite;
CacheUtils.saveSites = saveSites;
CacheUtils.saveCommitIds = saveCommitIds;
CacheUtils.readCommitId = readCommitId;
CacheUtils.clear = clear;

module.exports = CacheUtils;<|endoftext|>


<commit_before>define(["helper/Basic", "Tone/source/UserMedia", "Test", "Tone/source/Source"],
	function (BasicTests, UserMedia, Test, Source) {

	describe("UserMedia", function(){

		//run the common tests
		BasicTests(UserMedia);

		context("Source Tests", function(){

			it ("can connect the output", function(){
				var extIn = new UserMedia();
				extIn.connect(Test);
				extIn.dispose();
			});

			it ("can be constructed with the input number", function(){
				var extIn = new UserMedia();
				extIn.dispose();
			});

			it ("can be constructed with an options object", function(){
				var extIn = new UserMedia({
					"volume" : -10,
					"mute" : false
				});
				expect(extIn.volume.value).to.be.closeTo(-10, 0.1);
				expect(extIn.mute).to.be.false;
				extIn.dispose();
			});

			it ("indicates if the browser has UserMedia support", function(){
				expect(UserMedia.supported).to.be.a.boolean;
			});

		});

		//if it is a manual test (i.e. there is a person to 'allow' the microphone)
		if (UserMedia.supported){

			context("Opening and closing", function(){

				//long timeout to give testers time to allow the microphone
				this.timeout(100000);

				it ("open returns a promise", function(){
					var extIn = new UserMedia();
					var promise = extIn.open();
					expect(promise).to.be.instanceOf(Promise);
					return promise.then(function(){
						extIn.dispose();
					});
				});

				it ("can open an input", function(){
					var extIn = new UserMedia();
					return extIn.open().then(function(){
						extIn.dispose();
					});
				});

				it ("can open an input by name", function(){
					var extIn = new UserMedia();
					var name = null
					return UserMedia.enumerateDevices().then(function(devices){
						name = devices[0].deviceId
						return extIn.open(name)
					}).then(function(){
						expect(extIn.deviceId).to.equal(name);
						extIn.dispose();
					});
				});

				it ("can open an input by index", function(){
					var extIn = new UserMedia();
					return extIn.open(0).then(function(){
						extIn.dispose();
					});
				});

				it ("throws an error if it cant find the device name", function(){
					var extIn = new UserMedia();
					return extIn.open("doesn't exist").catch(function(){
						extIn.dispose();
					})
				});

				it ("is 'started' after media is open and 'stopped' otherwise", function(){
					var extIn = new UserMedia();
					expect(extIn.state).to.equal("stopped");
					return extIn.open().then(function(){
						expect(extIn.state).to.equal("started");
						extIn.dispose();
					});
				});

				it ("has a label, group and device id when open", function(){
					var extIn = new UserMedia();
					return extIn.open().then(function(){
						expect(extIn.deviceId).to.be.a("string");
						expect(extIn.groupId).to.be.a("string");
						expect(extIn.label).to.be.a("string");
						extIn.dispose();
					});
				});

				it ("can close an input", function(){
					var extIn = new UserMedia();
					return extIn.open().then(function(){
						extIn.close();
						extIn.dispose();
					});
				});

				it ("can enumerate devices", function(){
					return UserMedia.enumerateDevices().then(function(devices){
						expect(devices).to.be.instanceOf(Array);
					});
				});
			});
		}

	});
});
<commit_msg>use 'fake' flag for Firefox tests<commit_after>define(["helper/Basic", "Tone/source/UserMedia", "Test", "Tone/source/Source"],
	function (BasicTests, UserMedia, Test, Source) {

	describe("UserMedia", function(){

		//run the common tests
		BasicTests(UserMedia);

		context("Source Tests", function(){

			it ("can connect the output", function(){
				var extIn = new UserMedia();
				extIn.connect(Test);
				extIn.dispose();
			});

			it ("can be constructed with the input number", function(){
				var extIn = new UserMedia();
				extIn.dispose();
			});

			it ("can be constructed with an options object", function(){
				var extIn = new UserMedia({
					"volume" : -10,
					"mute" : false
				});
				expect(extIn.volume.value).to.be.closeTo(-10, 0.1);
				expect(extIn.mute).to.be.false;
				extIn.dispose();
			});

			it ("indicates if the browser has UserMedia support", function(){
				expect(UserMedia.supported).to.be.a.boolean;
			});

		});

		//if it is a manual test (i.e. there is a person to 'allow' the microphone)
		if (UserMedia.supported){

			context("Opening and closing", function(){

				//long timeout to give testers time to allow the microphone
				this.timeout(100000);

				//replace gUM for FF with 'fake : true' in the constraints
				var originalGetUserMedia = navigator.mediaDevices.getUserMedia
				navigator.mediaDevices.getUserMedia = function(constraints){
					constraints.fake = true
					return originalGetUserMedia.call(navigator.mediaDevices, constraints)
				}

				after(function(){
					navigator.mediaDevices.getUserMedia = originalGetUserMedia
				});

				function hasInputs(){
					return UserMedia.enumerateDevices().then(function(devices){
						return devices.length > 0
					})
				}

				it ("open returns a promise", function(){
					var extIn = new UserMedia();
					var promise = extIn.open();
					expect(promise).to.be.instanceOf(Promise);
					return promise.then(function(){
						extIn.dispose();
					});
				});

				it ("can open an input", function(){
					var extIn = new UserMedia();
					return extIn.open().then(function(){
						extIn.dispose();
					});
				});

				it ("can open an input by name", function(){
					var extIn = new UserMedia();
					var name = null
					return hasInputs().then(function(has){
						if (has){
							return UserMedia.enumerateDevices().then(function(devices){
								name = devices[0].deviceId
								return extIn.open(name)
							}).then(function(){
								expect(extIn.deviceId).to.equal(name);
								extIn.dispose();
							});
						}
					})
				});

				it ("can open an input by index", function(){
					var extIn = new UserMedia();
					return hasInputs().then(function(has){
						if (has){
							return extIn.open(0).then(function(){
								extIn.dispose();
							});
						}
					});
				});

				it ("throws an error if it cant find the device name", function(){
					var extIn = new UserMedia();
					return extIn.open("doesn't exist").then(function(){
						//shouldn't call 'then'
						throw new Error("shouldnt call 'then'");
					}).catch(function(){
						extIn.dispose();
					});
				});

				it ("is 'started' after media is open and 'stopped' otherwise", function(){
					var extIn = new UserMedia();
					expect(extIn.state).to.equal("stopped");
					return extIn.open().then(function(){
						expect(extIn.state).to.equal("started");
						extIn.dispose();
					});
				});

				it ("has a label, group and device id when open", function(){
					var extIn = new UserMedia();
					return extIn.open().then(function(){
						expect(extIn.deviceId).to.be.a("string");
						expect(extIn.groupId).to.be.a("string");
						expect(extIn.label).to.be.a("string");
						extIn.dispose();
					});
				});

				it ("can close an input", function(){
					var extIn = new UserMedia();
					return extIn.open().then(function(){
						extIn.close();
						extIn.dispose();
					});
				});

				it ("can enumerate devices", function(){
					return UserMedia.enumerateDevices().then(function(devices){
						expect(devices).to.be.instanceOf(Array);
					});
				});
			});
		}

	});
});
<|endoftext|>


<commit_before>describe('Grammar', function () {
  function itHas (objThunk, property, value) {
    var testName = 'has ' + property + ': ' + JSON.stringify(value);
    it(testName, function () {
      expect(objThunk()[property]).toEqual(value);
    });
  }

  function itsMethodReturns (objThunk, methodName, methodArg, expected) {
    var testName = methodName + '("' + methodArg + '") is ' + JSON.stringify(expected);
    it(testName, function () {
      expect(objThunk()[methodName](methodArg)).toEqual(expected);
    });
  }

  describe('.parse() with invalid/missing start rule', function () {
    it('throws when passed an invalid rule', function () {
      expect(SIP.Grammar.parse.bind(SIP.Grammar, '', 'an invalid rule')).toThrow();
    });

    it('defaults to parsing CRLF when passed no rule', function () {
      expect(SIP.Grammar.parse('\r\n')).toEqual({});
    });
  });

  var contactString = '"Iñaki @ł€" <SIP:+1234@ALIAX.net;Transport=WS>;+sip.Instance="abCD", sip:bob@biloxi.COM;headerParam, <sip:DOMAIN.com:5>';
  describe("Contacts parsed from '" + contactString + "'", function () {
    var contacts;

    beforeEach(function () {
      contacts = SIP.Grammar.parse(contactString, 'Contact');
      expect(contacts.length).toEqual(3);
    });

    describe('first contact', function () {
      var c1;

      beforeEach(function () {
        c1 = contacts[0].parsed;
      });

      it('is a NameAddrHeader', function () {
        expect(c1 instanceof(SIP.NameAddrHeader)).toBeTruthy();
      });

      it('has the display name', function () {
        expect(c1.display_name).toEqual('Iñaki @ł€');
      });

      it('has parameter +sip.instance set to "abCD"', function () {
        var paramName = '+sip.instance';
        expect(c1.hasParam(paramName)).toBeTruthy();
        expect(c1.getParam(paramName)).toEqual('"abCD"');
      });

      it('doesn\'t have parameter nooo', function () {
        var paramName = 'nooo';
        expect(c1.hasParam(paramName)).toBeFalsy();
        expect(c1.getParam(paramName)).toBeUndefined();
      });

      describe('its URI', function () {
        var uriThunk = function () { return c1.uri; };
        it('is a SIP.URI', function () {
          expect(uriThunk() instanceof(SIP.URI)).toBeTruthy();
        });

        var uriHas = itHas.bind(null, uriThunk);
        var uriReturns = itsMethodReturns.bind(null, uriThunk);

        uriHas('scheme', 'sip');
        uriHas('user', '+1234');
        uriHas('host', 'aliax.net');
        uriHas('port', undefined);

        uriReturns('getParam', 'transport', 'ws');
        uriReturns('getParam', 'foo', undefined);
        uriReturns('getHeader', 'X-Header', undefined);
      });

      it('can alter display name and URI parameters', function () {
        c1.display_name = '€€€';
        expect(c1.display_name).toEqual('€€€');
        c1.uri.user = '+999';
        expect(c1.uri.user).toEqual('+999');
        c1.setParam('+sip.instance', '"zxCV"');
        expect(c1.getParam('+SIP.instance')).toEqual('"zxCV"');
        c1.setParam('New-Param', null);
        expect(c1.hasParam('NEW-param')).toEqual(true);
        c1.uri.setParam('New-Param', null);
        expect(c1.toString()).toEqual('"€€€" <sip:+999@aliax.net;transport=ws;new-param>;+sip.instance="zxCV";new-param');
      });
    });

    describe('second contact', function () {
      var c2;

      beforeEach(function () {
        c2 = contacts[1].parsed;
      });

      var c2Thunk = function () { return c2; };
      var c2Has = itHas.bind(null, c2Thunk);
      var c2Returns = itsMethodReturns.bind(null, c2Thunk);

      c2Has('display_name', undefined);

      c2Returns('hasParam', 'HEADERPARAM', true);
      c2Returns('toString', null, '<sip:bob@biloxi.com>;headerparam');

      describe('its URI', function () {
        var uriThunk = function () { return c2.uri; };
        it('is a SIP.URI', function () {
          expect(uriThunk() instanceof(SIP.URI)).toBeTruthy();
        });

        var uriHas = itHas.bind(null, uriThunk);

        uriHas('scheme', 'sip');
        uriHas('user', 'bob');
        uriHas('host', 'biloxi.com');
        uriHas('port', undefined);

        itsMethodReturns(uriThunk, 'hasParam', 'headerParam', false);

        it('can alter display name', function () {
          c2.display_name = '@ł€ĸłæß';
          expect(c2.toString()).toEqual('"@ł€ĸłæß" <sip:bob@biloxi.com>;headerparam');
        });
      });
    });

    describe('third contact', function () {
      var c3;

      beforeEach(function () {
        c3 = contacts[2].parsed;
      });

      var c3Thunk = function () { return c3; };
      itHas(c3Thunk, 'display_name', undefined);
      itsMethodReturns(c3Thunk, 'toString', null, '<sip:domain.com:5>');

      describe('its URI', function () {
        var uriThunk = function () { return c3.uri; };
        it('is a SIP.URI', function () {
          expect(uriThunk() instanceof(SIP.URI)).toBeTruthy();
        });

        var uriHas = itHas.bind(null, uriThunk);

        uriHas('scheme', 'sip');
        uriHas('user', undefined);
        uriHas('host', 'domain.com');
        uriHas('port', 5);

        itsMethodReturns(uriThunk, 'hasParam', 'nooo', false);

        it('can set header params and uri params', function () {
          c3.uri.setParam('newUriParam', 'zxCV');
          c3.setParam('newHeaderParam', 'zxCV');
          expect(c3.toString()).toEqual('<sip:domain.com:5;newuriparam=zxcv>;newheaderparam=zxCV');
        });
      });
    });
  });

  var viaString = 'SIP /  3.0 \r\n / UDP [1:ab::FF]:6060 ;\r\n  BRanch=1234;Param1=Foo;paRAM2;param3=Bar';
  describe('Via parsed from "' + viaString + '"', function () {
    var via;

    beforeEach(function () {
      via = SIP.Grammar.parse(viaString, 'Via');
    });

    var viaHas = itHas.bind(null, function () { return via; });

    viaHas('protocol', 'SIP');
    viaHas('transport', 'UDP');
    viaHas('host', '[1:ab::FF]');
    viaHas('host_type', 'IPv6');
    viaHas('port', 6060);
    viaHas('branch', '1234');
    viaHas('params', {param1: 'Foo', param2: undefined, param3: 'Bar'});
  });

  var cseqString = '123456  CHICKEN';
  describe('CSeq parsed from "' + cseqString + '"', function () {
    var cseq;

    beforeEach(function () {
      cseq = SIP.Grammar.parse(cseqString, 'CSeq');
    });

    var cseqHas = itHas.bind(null, function () { return cseq; });

    cseqHas('value', 123456);
    cseqHas('method', 'CHICKEN');
  });

  var challengeString = 'Digest realm =  "[1:ABCD::abc]", nonce =  "31d0a89ed7781ce6877de5cb032bf114", qop="AUTH,autH-INt", algorithm =  md5  ,  stale =  TRUE , opaque = "00000188"';
  describe("challenge parsed from '" + challengeString + "'", function () {
    var challenge;

    beforeEach(function () {
      challenge = SIP.Grammar.parse(challengeString, 'challenge');
    });

    var challengeHas = itHas.bind(null, function () { return challenge; });

    challengeHas('realm', '[1:ABCD::abc]');
    challengeHas('nonce', '31d0a89ed7781ce6877de5cb032bf114');
    challengeHas('qop', ['auth', 'auth-int']);
    challengeHas('algorithm', 'MD5');
    challengeHas('stale', true);
    challengeHas('opaque', '00000188');
  });

  var eventString = 'Presence;Param1=QWe;paraM2';
  describe('Event parsed from "' + eventString + '"', function () {
    var evt;

    beforeEach(function () {
      evt = SIP.Grammar.parse(eventString, 'Event');
    });

    eventHas = itHas.bind(null, function () { return evt; });

    eventHas('event', 'presence');
    eventHas('params', {param1: 'QWe', param2: undefined});
  });
});
<commit_msg>Test parsing sips: Contact headers.<commit_after>describe('Grammar', function () {
  function itHas (objThunk, property, value) {
    var testName = 'has ' + property + ': ' + JSON.stringify(value);
    it(testName, function () {
      expect(objThunk()[property]).toEqual(value);
    });
  }

  function itsMethodReturns (objThunk, methodName, methodArg, expected) {
    var testName = methodName + '("' + methodArg + '") is ' + JSON.stringify(expected);
    it(testName, function () {
      expect(objThunk()[methodName](methodArg)).toEqual(expected);
    });
  }

  describe('.parse() with invalid/missing start rule', function () {
    it('throws when passed an invalid rule', function () {
      expect(SIP.Grammar.parse.bind(SIP.Grammar, '', 'an invalid rule')).toThrow();
    });

    it('defaults to parsing CRLF when passed no rule', function () {
      expect(SIP.Grammar.parse('\r\n')).toEqual({});
    });
  });

  var contactString = '"Iñaki @ł€" <SIP:+1234@ALIAX.net;Transport=WS>;+sip.Instance="abCD", sip:bob@biloxi.COM;headerParam, <sips:DOMAIN.com:5>';
  describe("Contacts parsed from '" + contactString + "'", function () {
    var contacts;

    beforeEach(function () {
      contacts = SIP.Grammar.parse(contactString, 'Contact');
      expect(contacts.length).toEqual(3);
    });

    describe('first contact', function () {
      var c1;

      beforeEach(function () {
        c1 = contacts[0].parsed;
      });

      it('is a NameAddrHeader', function () {
        expect(c1 instanceof(SIP.NameAddrHeader)).toBeTruthy();
      });

      it('has the display name', function () {
        expect(c1.display_name).toEqual('Iñaki @ł€');
      });

      it('has parameter +sip.instance set to "abCD"', function () {
        var paramName = '+sip.instance';
        expect(c1.hasParam(paramName)).toBeTruthy();
        expect(c1.getParam(paramName)).toEqual('"abCD"');
      });

      it('doesn\'t have parameter nooo', function () {
        var paramName = 'nooo';
        expect(c1.hasParam(paramName)).toBeFalsy();
        expect(c1.getParam(paramName)).toBeUndefined();
      });

      describe('its URI', function () {
        var uriThunk = function () { return c1.uri; };
        it('is a SIP.URI', function () {
          expect(uriThunk() instanceof(SIP.URI)).toBeTruthy();
        });

        var uriHas = itHas.bind(null, uriThunk);
        var uriReturns = itsMethodReturns.bind(null, uriThunk);

        uriHas('scheme', 'sip');
        uriHas('user', '+1234');
        uriHas('host', 'aliax.net');
        uriHas('port', undefined);

        uriReturns('getParam', 'transport', 'ws');
        uriReturns('getParam', 'foo', undefined);
        uriReturns('getHeader', 'X-Header', undefined);
      });

      it('can alter display name and URI parameters', function () {
        c1.display_name = '€€€';
        expect(c1.display_name).toEqual('€€€');
        c1.uri.user = '+999';
        expect(c1.uri.user).toEqual('+999');
        c1.setParam('+sip.instance', '"zxCV"');
        expect(c1.getParam('+SIP.instance')).toEqual('"zxCV"');
        c1.setParam('New-Param', null);
        expect(c1.hasParam('NEW-param')).toEqual(true);
        c1.uri.setParam('New-Param', null);
        expect(c1.toString()).toEqual('"€€€" <sip:+999@aliax.net;transport=ws;new-param>;+sip.instance="zxCV";new-param');
      });
    });

    describe('second contact', function () {
      var c2;

      beforeEach(function () {
        c2 = contacts[1].parsed;
      });

      var c2Thunk = function () { return c2; };
      var c2Has = itHas.bind(null, c2Thunk);
      var c2Returns = itsMethodReturns.bind(null, c2Thunk);

      c2Has('display_name', undefined);

      c2Returns('hasParam', 'HEADERPARAM', true);
      c2Returns('toString', null, '<sip:bob@biloxi.com>;headerparam');

      describe('its URI', function () {
        var uriThunk = function () { return c2.uri; };
        it('is a SIP.URI', function () {
          expect(uriThunk() instanceof(SIP.URI)).toBeTruthy();
        });

        var uriHas = itHas.bind(null, uriThunk);

        uriHas('scheme', 'sip');
        uriHas('user', 'bob');
        uriHas('host', 'biloxi.com');
        uriHas('port', undefined);

        itsMethodReturns(uriThunk, 'hasParam', 'headerParam', false);

        it('can alter display name', function () {
          c2.display_name = '@ł€ĸłæß';
          expect(c2.toString()).toEqual('"@ł€ĸłæß" <sip:bob@biloxi.com>;headerparam');
        });
      });
    });

    describe('third contact', function () {
      var c3;

      beforeEach(function () {
        c3 = contacts[2].parsed;
      });

      var c3Thunk = function () { return c3; };
      itHas(c3Thunk, 'display_name', undefined);
      itsMethodReturns(c3Thunk, 'toString', null, '<sips:domain.com:5>');

      describe('its URI', function () {
        var uriThunk = function () { return c3.uri; };
        it('is a SIP.URI', function () {
          expect(uriThunk() instanceof(SIP.URI)).toBeTruthy();
        });

        var uriHas = itHas.bind(null, uriThunk);

        uriHas('scheme', 'sips');
        uriHas('user', undefined);
        uriHas('host', 'domain.com');
        uriHas('port', 5);

        itsMethodReturns(uriThunk, 'hasParam', 'nooo', false);

        it('can set header params and uri params', function () {
          c3.uri.setParam('newUriParam', 'zxCV');
          c3.setParam('newHeaderParam', 'zxCV');
          expect(c3.toString()).toEqual('<sips:domain.com:5;newuriparam=zxcv>;newheaderparam=zxCV');
        });
      });
    });
  });

  var viaString = 'SIP /  3.0 \r\n / UDP [1:ab::FF]:6060 ;\r\n  BRanch=1234;Param1=Foo;paRAM2;param3=Bar';
  describe('Via parsed from "' + viaString + '"', function () {
    var via;

    beforeEach(function () {
      via = SIP.Grammar.parse(viaString, 'Via');
    });

    var viaHas = itHas.bind(null, function () { return via; });

    viaHas('protocol', 'SIP');
    viaHas('transport', 'UDP');
    viaHas('host', '[1:ab::FF]');
    viaHas('host_type', 'IPv6');
    viaHas('port', 6060);
    viaHas('branch', '1234');
    viaHas('params', {param1: 'Foo', param2: undefined, param3: 'Bar'});
  });

  var cseqString = '123456  CHICKEN';
  describe('CSeq parsed from "' + cseqString + '"', function () {
    var cseq;

    beforeEach(function () {
      cseq = SIP.Grammar.parse(cseqString, 'CSeq');
    });

    var cseqHas = itHas.bind(null, function () { return cseq; });

    cseqHas('value', 123456);
    cseqHas('method', 'CHICKEN');
  });

  var challengeString = 'Digest realm =  "[1:ABCD::abc]", nonce =  "31d0a89ed7781ce6877de5cb032bf114", qop="AUTH,autH-INt", algorithm =  md5  ,  stale =  TRUE , opaque = "00000188"';
  describe("challenge parsed from '" + challengeString + "'", function () {
    var challenge;

    beforeEach(function () {
      challenge = SIP.Grammar.parse(challengeString, 'challenge');
    });

    var challengeHas = itHas.bind(null, function () { return challenge; });

    challengeHas('realm', '[1:ABCD::abc]');
    challengeHas('nonce', '31d0a89ed7781ce6877de5cb032bf114');
    challengeHas('qop', ['auth', 'auth-int']);
    challengeHas('algorithm', 'MD5');
    challengeHas('stale', true);
    challengeHas('opaque', '00000188');
  });

  var eventString = 'Presence;Param1=QWe;paraM2';
  describe('Event parsed from "' + eventString + '"', function () {
    var evt;

    beforeEach(function () {
      evt = SIP.Grammar.parse(eventString, 'Event');
    });

    eventHas = itHas.bind(null, function () { return evt; });

    eventHas('event', 'presence');
    eventHas('params', {param1: 'QWe', param2: undefined});
  });
});
<|endoftext|>


<commit_before>/**
 * atomic.js
 */
describe('atomic', function () {

	/**
	 * xhr
	 */
	describe('xhr', function () {

		beforeEach(function () {
			spyOn(XMLHttpRequest.prototype, 'open').and.callThrough();
			spyOn(XMLHttpRequest.prototype, 'send');
			spyOn(XMLHttpRequest.prototype, 'setRequestHeader');
		});

		it('should open an XMLHttpRequest', function () {
			atomic.ajax({
				url: '/endpoint'
			})
				.success(function (data, xhr) {})
				.error(function (data, xhr) {})
				.always(function(data, xhr) {});
			expect(XMLHttpRequest.prototype.open).toHaveBeenCalled();
		});

		it('should send and XMLHttpRequest', function () {
			atomic.ajax({
				url: '/endpoint'
			})
				.success(function (data, xhr) {})
				.error(function (data, xhr) {});
			expect(XMLHttpRequest.prototype.send).toHaveBeenCalled();
		});

		it('should set request header', function(){
			atomic.ajax({
				url: '/endpoint'
			})
				.success(function (data, xhr) {})
				.error(function (data, xhr) {})
				.always(function(data, xhr){});
			expect(XMLHttpRequest.prototype.setRequestHeader).toHaveBeenCalled();
		});

	});

	describe('always', function() {

		it('should be called last after success or error', function(done) {
			var result = 0;
			atomic.ajax({
				url: '/endpoint'
			})
				.always(function(data, xhr) {
					result = 3;
				})
				.success(function(data, xhr) {
					result  = 1;
				})
				.error(function(data, xhr) {
					result  = 2;
				});
			setTimeout(function() {
				expect(result).toEqual(3);
				done();
			}, 100);
		});
	});

	describe('contentType', function(){

		beforeEach(function(){
			spyOn(XMLHttpRequest.prototype, 'setRequestHeader');
		});

		it('should use "application/x-www-form-urlencoded" as default Content-type', function(){
			atomic.ajax({
				url: '/endpoint'
			});

			expect(XMLHttpRequest.prototype.setRequestHeader)
					.toHaveBeenCalledWith('Content-type', 'application/x-www-form-urlencoded');
		});

		it('should set Content-type', function() {
			atomic.ajax({
				url: '/endpoint',
				contentType: 'application/json'
			});

			expect(XMLHttpRequest.prototype.setRequestHeader)
					.toHaveBeenCalledWith('Content-type', 'application/json');
		});

	});

});<commit_msg>Fixed unit test<commit_after>/**
 * atomic.js
 */
describe('atomic', function () {

	/**
	 * xhr
	 */
	describe('xhr', function () {

		beforeEach(function () {
			spyOn(XMLHttpRequest.prototype, 'open').and.callThrough();
			spyOn(XMLHttpRequest.prototype, 'send');
			spyOn(XMLHttpRequest.prototype, 'setRequestHeader');
		});

		it('should open an XMLHttpRequest', function () {
			atomic.ajax({
				url: '/endpoint'
			})
				.success(function (data, xhr) {})
				.error(function (data, xhr) {})
				.always(function(data, xhr) {});
			expect(XMLHttpRequest.prototype.open).toHaveBeenCalled();
		});

		it('should send and XMLHttpRequest', function () {
			atomic.ajax({
				url: '/endpoint'
			})
				.success(function (data, xhr) {})
				.error(function (data, xhr) {});
			expect(XMLHttpRequest.prototype.send).toHaveBeenCalled();
		});

		it('should set request header', function(){
			atomic.ajax({
				url: '/endpoint'
			})
				.success(function (data, xhr) {})
				.error(function (data, xhr) {})
				.always(function(data, xhr){});
			expect(XMLHttpRequest.prototype.setRequestHeader).toHaveBeenCalled();
		});

	});

	describe('always', function() {

		it('should be called last after success or error', function(done) {
			var result = 0;
			atomic.ajax({
				url: '/endpoint'
			})
				.always(function(data, xhr) {
					result = 3;
				})
				.success(function(data, xhr) {
					result  = 1;
				})
				.error(function(data, xhr) {
					result  = 2;
				});
			setTimeout(function() {
				expect(result).toEqual(3);
				done();
			}, 100);
		});
	});

	describe('contentType', function(){

		beforeEach(function(){
			spyOn(XMLHttpRequest.prototype, 'setRequestHeader');
		});

		it('should use "application/x-www-form-urlencoded" as default Content-type', function(){
			atomic.ajax({
				url: '/endpoint'
			});

			expect(XMLHttpRequest.prototype.setRequestHeader)
					.toHaveBeenCalledWith('Content-type', 'application/x-www-form-urlencoded');
		});

		it('should set Content-type', function() {
			atomic.ajax({
				url: '/endpoint',
				headers: {
					'Content-type': 'application/json'
				}
			});

			expect(XMLHttpRequest.prototype.setRequestHeader)
					.toHaveBeenCalledWith('Content-type', 'application/json');
		});

	});

});<|endoftext|>


<commit_before>/* File: tag.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';

/*jshint unused: true */
/*exported utils, Tag */

var utils = require('./utils'),
	request = require('supertest'),
	express = require('express'),
	Tag = require('../../../models/Tag'),
	tagDao = require('../../../api/dao/tag'),
	app = express();

var tag1 = {
	_id: '52e2551694d6f1312355ba9e',
	libelle: 'Exercie'
};

describe('Dao:Tag', function() {

	it('Dao:Tag:Create', function(done) {
		app.post('/addTag', function(req, res) {
			req.body = {
				tag: tag1
			};
			tagDao.create(req, res);
		});
		request(app).post('/addTag').expect(200, done);
	});

	it('Dao:Tag:Update', function(done) {
		app.post('/updateTag', function(req, res) {
			req.body = {
				tag: {
					_id: tag1._id,
					libelle: 'Cours'
				}
			};
			tagDao.update(req, res);
		});
		request(app).post('/updateTag').expect(200, done);
	});

	it('Dao:Tag:All', function(done) {
		app.post('/readTags', function(req, res) {
			tagDao.all(req, res);
		});
		request(app).post('/readTags').expect(200, done);
	});

	it('Dao:Tag:FindTagById', function(done) {
		app.post('/getTagById', function(req, res) {
			req.body = {
				idTag: tag1._id,
				position: 1
			};
			tagDao.findTagById(req, res);
		});
		request(app).post('/getTagById').expect(200, done);
	});

	it('Dao:Tag:Remove', function(done) {
		app.post('/deleteTag', function(req, res) {
			req.body = {
				deleteTag: tag1
			};
			tagDao.remove(req, res);
		});
		request(app).post('/deleteTag').expect(200, done);
	});
});<commit_msg>commenté tous les test des tags<commit_after>/* File: tag.js
 *
 * Copyright (c) 2014
 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France
 * (direction-innovation@cned.fr)
 *
 * GNU Affero General Public License (AGPL) version 3.0 or later version
 *
 * This file is part of a program which is free software: you can
 * redistribute it and/or modify it under the terms of the
 * GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 *
 */

'use strict';

/*jshint unused: true */
/*exported utils, Tag */

var utils = require('./utils'),
	request = require('supertest'),
	express = require('express'),
	Tag = require('../../../models/Tag'),
	tagDao = require('../../../api/dao/tag'),
	app = express();

var tag1 = {
	_id: '52e2551694d6f1312355ba9e',
	libelle: 'Exercie'
};

describe('Dao:Tag', function() {

    // it('Dao:Tag:Create', function(done) {
    // 	app.post('/addTag', function(req, res) {
    // 		req.body = {
    // 			tag: tag1
    // 		};
    // 		tagDao.create(req, res);
    // 	});
    // 	request(app).post('/addTag').expect(200, done);
    // });

    // it('Dao:Tag:Update', function(done) {
    // 	app.post('/updateTag', function(req, res) {
    // 		req.body = {
    // 			tag: {
    // 				_id: tag1._id,
    // 				libelle: 'Cours'
    // 			}
    // 		};
    // 		tagDao.update(req, res);
    // 	});
    // 	request(app).post('/updateTag').expect(200, done);
    // });

    // it('Dao:Tag:All', function(done) {
    // 	app.post('/readTags', function(req, res) {
    // 		tagDao.all(req, res);
    // 	});
    // 	request(app).post('/readTags').expect(200, done);
    // });

    // it('Dao:Tag:FindTagById', function(done) {
    // 	app.post('/getTagById', function(req, res) {
    // 		req.body = {
    // 			idTag: tag1._id,
    // 			position: 1
    // 		};
    // 		tagDao.findTagById(req, res);
    // 	});
    // 	request(app).post('/getTagById').expect(200, done);
    // });

    // it('Dao:Tag:Remove', function(done) {
    // 	app.post('/deleteTag', function(req, res) {
    // 		req.body = {
    // 			deleteTag: tag1
    // 		};
    // 		tagDao.remove(req, res);
    // 	});
    // 	request(app).post('/deleteTag').expect(200, done);
    // });
});<|endoftext|>