<commit_before>/*
 * Copyright (c) 2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jshint eqeqeq: false*/

/**
Provides a set of features
to control a YUI instance on the client side. This module will be
serialized and sent to the client side thru `res.expose()` and available
in the client side thru `window.app.yui`.

@module express-yui/lib/client
**/

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

/**
Provides a set of methods to be serialized and sent to the client side to boot
the application in the browser.

@class client
@static
@uses utils
@extensionfor express-yui/lib/yui
*/
function bootstrap(method, args) {

    var self = this,
        d = document,
        head = d.getElementsByTagName('head')[0],
        // Some basic browser sniffing...
        ie = /MSIE/.test(navigator.userAgent),
        // number of seed parts that are still pending
        pending = 0,
        // it is just a queue of pending "use" statements until YUI gets ready
        callback = [],
        config = typeof YUI_config != "undefined" ? YUI_config : {};

    function flush() {
        var l = callback.length,
            i;
        if (!self.YUI && typeof YUI == "undefined") {
            throw new Error("YUI was not injected correctly!");
        }
        self.YUI = self.YUI || YUI;
        // callback on every pending use statement
        for (i = 0; i < l; i++) {
            callback.shift()();
        }
    }

    function decrementRequestPending() {
        pending--;
        if (pending <= 0) {
            setTimeout(flush, 0);
        } else {
            // in case there is any remaining script to be loaded
            load();
        }
    }

    function createScriptNode(src) {
        var node = d.createElement('script');
        // use async=false for ordered async?
        // parallel-load-serial-execute http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
        if (node.async) {
            node.async = false;
        }
        if (ie) {
            node.onreadystatechange = function () {
                if (/loaded|complete/.test(this.readyState)) {
                    this.onreadystatechange = null;
                    decrementRequestPending();
                }
            };
        } else {
            node.onload = node.onerror = decrementRequestPending;
        }
        node.setAttribute('src', src);
        return node;
    }

    function load() {
        if (!config.seed) {
            throw new Error('YUI_config.seed array is required.');
        }
        var seed = config.seed,
            l = seed.length,
            i, node;

        pending = pending || seed.length;
        // flagging the injection process to avoid duplicated entries
        self._injected = true;

        // appending every file from seed collection into the header
        for (i = 0; i < l; i++) {
            node = createScriptNode(seed.shift());
            head.appendChild(node);
            // TODO: if original node.async is undefined, it means the order has
            // to be preserved manually, in which case we should insert
            // them one by one to guarantee serial execute
            if (node.async !== false) {
                break;
            }
        }

    }

    callback.push(function () {
        var i;

        if (!self._Y) {
            // extend core (YUI_config.extendedCore)
            self.YUI.Env.core.push.apply(self.YUI.Env.core, config.extendedCore || []);
            // create unique instance which is accesible thru app.yui.use()
            self._Y = self.YUI();
            self.use = self._Y.use;

            if (config.patches && config.patches.length) {
                for (i = 0; i < config.patches.length; i += 1) {
                    config.patches[i](self._Y, self._Y.Env._loader);
                }
            }
        }
        // call use/require with arguments
        self._Y[method].apply(self._Y, args);
    });

    // just in case YUI was injected manually in the page
    self.YUI = self.YUI || (typeof YUI != "undefined" ? YUI : null);

    if (!self.YUI && !self._injected) {
        // attach seed and wait for it to finish to flush the callback
        load();
    } else if (pending <= 0) {
        // everything is ready, just flush
        flush();
    } // else do nothing, the current pending job will take care of flushing callback

    return this; // chaining
}

module.exports = {

    /**
    Attaches the seed into the head, then creates a YUI Instance and attaches
    `modules` into it. This is equivalent to `YUI().use()` after getting the seed
    ready. This method is a bootstrap implementation for the library, and the way
    you use this in your templates, is by doing this:

        <script>{{{state}}}</script>
        <script>
        app.yui.use('foo', 'bar', function (Y) {
            // do something!
        });
        </script>

    Where `state` defines the state of the express app, and `app.yui` defines
    the helpers that `express-yui` brings into the client side.

    @method use
    @public
    @chainable
    **/
    use: utils.minifyFunction(function () {
        return this._bootstrap('use', [].slice.call(arguments));
    }),

    /**
    Like `app.yui.use()` but instead delegates to `YUI().require()` after
    getting the seed ready. The callback passed to `require()` receives two
    arguments, the `Y` object like `use()`, but also `imports` which holds all
    of the exports from the required modules.

        <script>{{{state}}}</script>
        <script>
        app.yui.require('foo', 'bar', function (Y, imports) {
            var Foo         = imports['foo'],
                namedExport = imports['bar'].baz;
        });
        </script>

    @method require
    @public
    **/
    require: utils.minifyFunction(function () {
        this._bootstrap('require', [].slice.call(arguments));
    }),

    /**
    Boots the application, rehydrate the app state and calls back to notify the
    `ready` state of the app.

        <script>{{{state}}}</script>
        <script>
        app.yui.ready(function (err) {
            if (err) {
                throw err;
            }
            app.yui.use('foo', 'bar', function (Y) {
                // do something!
            });
        });
        </script>

    @method ready
    @param {Function} callback when the app is ready. If an error occurr, the error object
                        will be passed as the first argument of the callback function.
    @public
    **/
    ready: utils.minifyFunction(function (callback) {
        this.use(function () {
            callback();
        });
    }),

    /**
    The internal bootstraping implementation.

    @method _bootstrap
    @param {String} method The method to call on `Y`, either `"use"` or `"require"`.
    @param {Any[]} args Array of `arguments` to apply to the `Y` `method`.
    @private
    */
    _bootstrap: utils.minifyFunction(bootstrap)
};
<commit_msg>supporting multiple calls to use() and ready()<commit_after>/*
 * Copyright (c) 2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jshint eqeqeq: false*/

/**
Provides a set of features
to control a YUI instance on the client side. This module will be
serialized and sent to the client side thru `res.expose()` and available
in the client side thru `window.app.yui`.

@module express-yui/lib/client
**/

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

/**
Provides a set of methods to be serialized and sent to the client side to boot
the application in the browser.

@class client
@static
@uses utils
@extensionfor express-yui/lib/yui
*/
function bootstrap(method, args) {

    var self = this,
        d = document,
        head = d.getElementsByTagName('head')[0],
        // Some basic browser sniffing...
        ie = /MSIE/.test(navigator.userAgent),
        // it is just a queue of pending "use" statements until YUI gets ready
        callback = [],
        config = typeof YUI_config != "undefined" ? YUI_config : {};

    function flush() {
        var l = callback.length,
            i;
        if (!self.YUI && typeof YUI == "undefined") {
            throw new Error("YUI was not injected correctly!");
        }
        self.YUI = self.YUI || YUI;
        // callback on every pending use statement
        for (i = 0; i < l; i++) {
            callback.shift()();
        }
    }

    function decrementRequestPending() {
        self._pending--;
        if (self._pending <= 0) {
            setTimeout(flush, 0);
        } else {
            // in case there is any remaining script to be loaded
            load();
        }
    }

    function createScriptNode(src) {
        var node = d.createElement('script');
        // use async=false for ordered async?
        // parallel-load-serial-execute http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
        if (node.async) {
            node.async = false;
        }
        if (ie) {
            node.onreadystatechange = function () {
                if (/loaded|complete/.test(this.readyState)) {
                    this.onreadystatechange = null;
                    decrementRequestPending();
                }
            };
        } else {
            node.onload = node.onerror = decrementRequestPending;
        }
        node.setAttribute('src', src);
        return node;
    }

    function load() {
        if (!config.seed) {
            throw new Error('YUI_config.seed array is required.');
        }
        var seed = config.seed,
            l = seed.length,
            i, node;

        if (!self._injected) {
            // flagging the injection process to avoid duplicated entries
            self._injected = true;
            self._pending = seed.length;
        }

        // appending every file from seed collection into the header
        for (i = 0; i < l; i++) {
            node = createScriptNode(seed.shift());
            head.appendChild(node);
            // TODO: if original node.async is undefined, it means the order has
            // to be preserved manually, in which case we should insert
            // them one by one to guarantee serial execute
            if (node.async !== false) {
                break;
            }
        }

    }

    callback.push(function () {
        var i;

        if (!self._Y) {
            // extend core (YUI_config.extendedCore)
            self.YUI.Env.core.push.apply(self.YUI.Env.core, config.extendedCore || []);
            // create unique instance which is accesible thru app.yui.use()
            self._Y = self.YUI();
            self.use = self._Y.use;

            if (config.patches && config.patches.length) {
                for (i = 0; i < config.patches.length; i += 1) {
                    config.patches[i](self._Y, self._Y.Env._loader);
                }
            }
        }
        // call use/require with arguments
        self._Y[method].apply(self._Y, args);
    });

    // just in case YUI was injected manually in the page
    self.YUI = self.YUI || (typeof YUI != "undefined" ? YUI : null);

    if (!self.YUI && !self._injected) {
        // attach seed and wait for it to finish to flush the callback
        load();
    } else if (self._pending <= 0) {
        // everything is ready, just flush on the next tick
        setTimeout(flush, 0);
    } // else do nothing, the current pending job will take care of flushing callback

    return this; // chaining
}

module.exports = {

    /**
    Attaches the seed into the head, then creates a YUI Instance and attaches
    `modules` into it. This is equivalent to `YUI().use()` after getting the seed
    ready. This method is a bootstrap implementation for the library, and the way
    you use this in your templates, is by doing this:

        <script>{{{state}}}</script>
        <script>
        app.yui.use('foo', 'bar', function (Y) {
            // do something!
        });
        </script>

    Where `state` defines the state of the express app, and `app.yui` defines
    the helpers that `express-yui` brings into the client side.

    @method use
    @public
    @chainable
    **/
    use: utils.minifyFunction(function () {
        return this._bootstrap('use', [].slice.call(arguments));
    }),

    /**
    Like `app.yui.use()` but instead delegates to `YUI().require()` after
    getting the seed ready. The callback passed to `require()` receives two
    arguments, the `Y` object like `use()`, but also `imports` which holds all
    of the exports from the required modules.

        <script>{{{state}}}</script>
        <script>
        app.yui.require('foo', 'bar', function (Y, imports) {
            var Foo         = imports['foo'],
                namedExport = imports['bar'].baz;
        });
        </script>

    @method require
    @public
    **/
    require: utils.minifyFunction(function () {
        this._bootstrap('require', [].slice.call(arguments));
    }),

    /**
    Boots the application, rehydrate the app state and calls back to notify the
    `ready` state of the app.

        <script>{{{state}}}</script>
        <script>
        app.yui.ready(function (err) {
            if (err) {
                throw err;
            }
            app.yui.use('foo', 'bar', function (Y) {
                // do something!
            });
        });
        </script>

    @method ready
    @param {Function} callback when the app is ready. If an error occurr, the error object
                        will be passed as the first argument of the callback function.
    @public
    **/
    ready: utils.minifyFunction(function (callback) {
        this.use(function () {
            callback();
        });
    }),

    /**
    The internal bootstraping implementation.

    @method _bootstrap
    @param {String} method The method to call on `Y`, either `"use"` or `"require"`.
    @param {Any[]} args Array of `arguments` to apply to the `Y` `method`.
    @private
    */
    _bootstrap: utils.minifyFunction(bootstrap)
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017 Laura Taylor (https://github.com/techstreams)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

'use strict';

// Configuration - Cloud Functions
const fbTokenPath = '/function-token'
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)

// Configuration - Cloud Storage
const gcs = require('@google-cloud/storage')()
const bucket = gcs.bucket(functions.config().firebase.storageBucket)

// Configuration - Express
const express = require('express')
const app = express()

// Request Method Validation Middleware
const allowMethods = (req, res, next) => {
  const methods = ['GET','POST']
  if (methods.indexOf(req.method.toUpperCase()) === -1) {
    res.header('Allow', methods.join(', '))
    res.status(405).send('Request Method Not Allowed')
    return
  }
  next()
}

// Token validation middleware
const validateToken = (req, res, next) => {
  if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ') || !req.headers.authorization.split('Bearer ')[1]) {
    console.error('Unauthorized Request.  No Token was Passed in the Authorization Header.')
    res.status(403).send('Unauthorized')
    return
  }
  const reqToken = req.headers.authorization.split('Bearer ')[1]
  admin.database().ref(fbTokenPath).once('value').then(snapshot => {
    const fbToken = snapshot.val()
    if (!fbToken) {
      console.log('No Function Token Found in Firebase')
      res.status(403).send('Unauthorized')
      return
    }
    if (reqToken != fbToken) {
      console.log(`Unauthorized Token: ${reqToken}`)
      res.status(403).send('Unauthorized')
      return
    }
    next()
  }).catch(error => {
    console.log(`Authorization Error: ${error}`)
    res.status(403).send('Unauthorized')
  })
}

// Use Middleware
app.use(allowMethods)
app.use(validateToken)

// Handle Get Request
app.get('/:path/:filename', (req, res) => {
  const file = bucket.file(req.params.path + '/' + req.params.filename)
  file.exists().then(data => {
    if (!data[0]) {
      res.status(404).send('Not Found')
    }
    return file.download()
  }).then(content => {
    res.status(200).send(content[0])
  }).catch(err => {
    console.log(`Error Retrieving File: ${err}`)
    res.status(500).send('Server Error')
  })
})

// Handle Post Request
app.post('/:path/:filename', (req, res) => {
  // Ensure Content and Content-Type matches 'text/*'
  if (req.body && req.body != '' && req.is('text/*')) {
    const file = bucket.file(req.params.path + '/' + req.params.filename)
    const options = {
      metadata: {
        contentType: req.get('content-type')
      }
    }
    file.save(req.body, options).then(() => {
      res.status(200).send('File Saved')
    }).catch(err => {
      console.log(`Error Saving File to Storage: ${err}`)
      res.status(500).send('Server Error')
    })
  } else {
    console.log('No File Content or Invalide Content-Type')
    res.status(400).send('Bad Request')
  }
})

// Send a 400 for non-matching get requests
app.get('*', (req, res) => {
  res.status(400).send('Bad Request')
})

// Send a 400 for non-matching post requests
app.post('*', (req, res) => {
  res.status(400).send('Bad Request')
})

// Export Function
exports.textStorage = functions.https.onRequest(app)
<commit_msg>Fix typo<commit_after>/**
 * Copyright (c) 2017 Laura Taylor (https://github.com/techstreams)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

'use strict';

// Configuration - Cloud Functions
const fbTokenPath = '/function-token'
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)

// Configuration - Cloud Storage
const gcs = require('@google-cloud/storage')()
const bucket = gcs.bucket(functions.config().firebase.storageBucket)

// Configuration - Express
const express = require('express')
const app = express()

// Request Method Validation Middleware
const allowMethods = (req, res, next) => {
  const methods = ['GET','POST']
  if (methods.indexOf(req.method.toUpperCase()) === -1) {
    res.header('Allow', methods.join(', '))
    res.status(405).send('Request Method Not Allowed')
    return
  }
  next()
}

// Token validation middleware
const validateToken = (req, res, next) => {
  if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ') || !req.headers.authorization.split('Bearer ')[1]) {
    console.error('Unauthorized Request.  No Token was Passed in the Authorization Header.')
    res.status(403).send('Unauthorized')
    return
  }
  const reqToken = req.headers.authorization.split('Bearer ')[1]
  admin.database().ref(fbTokenPath).once('value').then(snapshot => {
    const fbToken = snapshot.val()
    if (!fbToken) {
      console.log('No Function Token Found in Firebase')
      res.status(403).send('Unauthorized')
      return
    }
    if (reqToken != fbToken) {
      console.log(`Unauthorized Token: ${reqToken}`)
      res.status(403).send('Unauthorized')
      return
    }
    next()
  }).catch(error => {
    console.log(`Authorization Error: ${error}`)
    res.status(403).send('Unauthorized')
  })
}

// Use Middleware
app.use(allowMethods)
app.use(validateToken)

// Handle Get Request
app.get('/:path/:filename', (req, res) => {
  const file = bucket.file(req.params.path + '/' + req.params.filename)
  file.exists().then(data => {
    if (!data[0]) {
      res.status(404).send('Not Found')
    }
    return file.download()
  }).then(content => {
    res.status(200).send(content[0])
  }).catch(err => {
    console.log(`Error Retrieving File: ${err}`)
    res.status(500).send('Server Error')
  })
})

// Handle Post Request
app.post('/:path/:filename', (req, res) => {
  // Ensure Content and Content-Type matches 'text/*'
  if (req.body && req.body != '' && req.is('text/*')) {
    const file = bucket.file(req.params.path + '/' + req.params.filename)
    const options = {
      metadata: {
        contentType: req.get('content-type')
      }
    }
    file.save(req.body, options).then(() => {
      res.status(200).send('File Saved')
    }).catch(err => {
      console.log(`Error Saving File to Storage: ${err}`)
      res.status(500).send('Server Error')
    })
  } else {
    console.log('No File Content or Invalid Content-Type')
    res.status(400).send('Bad Request')
  }
})

// Send a 400 for non-matching get requests
app.get('*', (req, res) => {
  res.status(400).send('Bad Request')
})

// Send a 400 for non-matching post requests
app.post('*', (req, res) => {
  res.status(400).send('Bad Request')
})

// Export Function
exports.textStorage = functions.https.onRequest(app)
<|endoftext|>


<commit_before>const faker = require('faker');
const {Map} = require('immutable');

const {RatioMap} = require('../ratio_map');

class ReqGenerator {
  constructor(reqParams) {
    const reqs = reqParams
      .map((p) => Map(p))
      .map((p) => p.update('statusRatio', (rs) => new RatioMap(rs)))
      .reduce((map, param) => map.set(param.delete('ratio'), param.get('ratio')), Map());
    this.reqRatio = new RatioMap(reqs);
  }

  randomRequest() {
    const req    = this.reqRatio.randomKey();
    const status = req.get('statusRatio').randomKey();
    return req.delete('statusRatio').set('status', status);
  }
}

class CrudReqGenerator extends ReqGenerator {
  constructor(crudParam) {
    const reqParams = Map(crudParam.methodRatio)
      .map(({ratio, statusRatio}, method) => {
        return {method: method, path: `/v1/${crudParam.resource}`, ratio, statusRatio};
      })
      .toList();
    super(reqParams);

    this.resource = crudParam.resource;
  }

  randomRequest(id) {
    return super.randomRequest().update('path', (path) => `${path}/${id}`);
  }
}

module.exports = {
  CrudReqGenerator,
  ReqGenerator,
};
<commit_msg>Add validation of CrudReqGenerator.randomRequest()<commit_after>const faker = require('faker');
const {Map} = require('immutable');
const is    = require('is_js');

const {RatioMap} = require('../ratio_map');

class ReqGenerator {
  constructor(reqParams) {
    const reqs = reqParams
      .map((p) => Map(p))
      .map((p) => p.update('statusRatio', (rs) => new RatioMap(rs)))
      .reduce((map, param) => map.set(param.delete('ratio'), param.get('ratio')), Map());
    this.reqRatio = new RatioMap(reqs);
  }

  randomRequest() {
    const req    = this.reqRatio.randomKey();
    const status = req.get('statusRatio').randomKey();
    return req.delete('statusRatio').set('status', status);
  }
}

class CrudReqGenerator extends ReqGenerator {
  constructor(crudParam) {
    const reqParams = Map(crudParam.methodRatio)
      .map(({ratio, statusRatio}, method) => {
        return {method: method, path: `/v1/${crudParam.resource}`, ratio, statusRatio};
      })
      .toList();
    super(reqParams);

    this.resource = crudParam.resource;
  }

  randomRequest(id) {
    if (is.not.string(id)) {
      throw new Error('1st argument(id) must be "String"');
    }
    return super.randomRequest().update('path', (path) => `${path}/${id}`);
  }
}

module.exports = {
  CrudReqGenerator,
  ReqGenerator,
};
<|endoftext|>


<commit_before>
var tape = require('tape')

var Layered = require('../')

var layered = Layered()
var cont = require('cont')

layered.use({
  name: 'foo',
  version: '1.0.0',
  manifest: { foo: 'async' },
  core: true,
  init: function (api) {
    return {
      foo: cont(function (val, cb) {
        cb(null, 'FOO'+val)
      })
    }
  }
}).use({
  name: 'bar',
  version: '0.0.0',
  manifest: { bar: 'async' },
  dependencies: {
    foo: '1.0',
  },
  core: true,
  init: function (api) {
    return {
      bar: cont(function (val, cb) {
        this.foo(val+'BAR', cb)
      })
    }
  }
})

tape('simple', function (t) {

  var api = layered.api()

  api.foo('hello', function (err, val) {
    t.equal(val, 'FOOhello')
    api.bar('hello', function (err, val) {
      t.equal(val, 'FOOhelloBAR')
      t.end()
    })
  })

})

tape('permissions', function (t) {

  t.plan(10)

  function perms () { }

  perms.pre = function (v, path, type) {
    t.equal(v, 'hello')
    t.deepEqual(path, ['foo'])
    t.equal('async', type)
  }

  perms.post = function (v, path, type) {
    t.equal(type, 'async')
    return function (cb) {
      v(function (err, value) {
        t.equal(value, 'FOOhello')
        t.deepEqual(path, ['foo'])
        t.equal('async', type)
        cb(err, value)
      })
    }
  }

  t.deepEqual(layered.manifest(), {
    foo: 'async',
    bar: 'async'
  })

  var api = layered.api(perms)

  api.foo('hello', function (err, v) {
    t.notOk(err)
    t.equal(v,'FOOhello')
    t.end()
  })

})

tape('nested', function (t) {

  t.plan(23)

  var pre = 0, post = 2

  layered.use({
    name: 'baz',
    version: '0.0.0',
    manifest: { foobar: 'async' },
    dependencies: {
      foo: '1.0',
      bar: '~0.0.0'
    },
    core: false,
    init: function (api) {
      return {
        foobar: cont(function (val, cb) {
          this.bar(val, cb)
        })
      }
    }
  })

  function perms () { }

  var expectedPaths = [
    ['baz', 'foobar'],
    ['bar'],
    ['foo']
  ]

  var expectedArg = [
    'hi', 'hi', 'hiBAR'
  ]

  perms.pre = function (v, path, type) {
    t.equal(v, expectedArg[pre])
    t.deepEqual(path, expectedPaths[pre++], 'pre-path is correct')
    t.equal('async', type)
  }

  perms.post = function (v, path, type) {
    t.equal(type, 'async')
    return function (cb) {
      v(function (err, value) {
        console.log("POST", post, path, type)
        t.equal(value, 'FOOhiBAR')
        t.deepEqual(path, expectedPaths[post--], 'post-path is correct')
        t.equal('async', type)
        cb(err, value)
      })
    }
  }

  t.deepEqual(layered.manifest(), {
    foo: 'async',
    bar: 'async',
    baz: { foobar: 'async' }
  })

  var api = layered.api(perms)

  api.baz.foobar('hi', function (err, v) {
    t.equal(v,'FOOhiBAR')
    t.end()
  })

})

<commit_msg>test config<commit_after>
var tape = require('tape')
var cont = require('cont')

var Layered = require('../')

var config = {
  foo: true, bar: 1, baz: 'hello'
}

var layered = Layered(config)

layered.use({
  name: 'foo',
  version: '1.0.0',
  manifest: { foo: 'async' },
  core: true,
  init: function (api) {
    return {
      foo: cont(function (val, cb) {
        cb(null, 'FOO'+val)
      })
    }
  }
}).use({
  name: 'bar',
  version: '0.0.0',
  manifest: { bar: 'async' },
  dependencies: {
    foo: '1.0',
  },
  core: true,
  init: function (api) {
    return {
      bar: cont(function (val, cb) {
        this.foo(val+'BAR', cb)
      })
    }
  }
})

tape('simple', function (t) {

  var api = layered.api()

  api.foo('hello', function (err, val) {
    t.equal(val, 'FOOhello')
    api.bar('hello', function (err, val) {
      t.equal(val, 'FOOhelloBAR')
      t.end()
    })
  })

})

tape('permissions', function (t) {

  t.plan(10)

  function perms () { }

  perms.pre = function (v, path, type) {
    t.equal(v, 'hello')
    t.deepEqual(path, ['foo'])
    t.equal('async', type)
  }

  perms.post = function (v, path, type) {
    t.equal(type, 'async')
    return function (cb) {
      v(function (err, value) {
        t.equal(value, 'FOOhello')
        t.deepEqual(path, ['foo'])
        t.equal('async', type)
        cb(err, value)
      })
    }
  }

  t.deepEqual(layered.manifest(), {
    foo: 'async',
    bar: 'async'
  })

  var api = layered.api(perms)

  api.foo('hello', function (err, v) {
    t.notOk(err)
    t.equal(v,'FOOhello')
    t.end()
  })

})

tape('nested', function (t) {

  t.plan(24)

  var pre = 0, post = 2

  layered.use({
    name: 'baz',
    version: '0.0.0',
    manifest: { foobar: 'async' },
    dependencies: {
      foo: '1.0',
      bar: '~0.0.0'
    },
    core: false,
    init: function (api, _config) {
      t.deepEqual(_config, config)
      return {
        foobar: cont(function (val, cb) {
          this.bar(val, cb)
        })
      }
    }
  })

  function perms () { }

  var expectedPaths = [
    ['baz', 'foobar'],
    ['bar'],
    ['foo']
  ]

  var expectedArg = [
    'hi', 'hi', 'hiBAR'
  ]

  perms.pre = function (v, path, type) {
    t.equal(v, expectedArg[pre])
    t.deepEqual(path, expectedPaths[pre++], 'pre-path is correct')
    t.equal('async', type)
  }

  perms.post = function (v, path, type) {
    t.equal(type, 'async')
    return function (cb) {
      v(function (err, value) {
        console.log("POST", post, path, type)
        t.equal(value, 'FOOhiBAR')
        t.deepEqual(path, expectedPaths[post--], 'post-path is correct')
        t.equal('async', type)
        cb(err, value)
      })
    }
  }

  t.deepEqual(layered.manifest(), {
    foo: 'async',
    bar: 'async',
    baz: { foobar: 'async' }
  })

  var api = layered.api(perms)

  api.baz.foobar('hi', function (err, v) {
    t.equal(v,'FOOhiBAR')
    t.end()
  })

})

<|endoftext|>


<commit_before>var CONTAINERS = {
  LOCK: 1,
  CODE: 2,
  OUTPUT: 3
};

var currentLockContainerSelector;
var remember;

function bindEvents () {
  hljs.configure({
    classPrefix: ''
  });

  $('form input, form textarea').on('change keydown keypress keyup mousedown click mouseup', function() {
    updateShownLock();
  });

  $('form select').on('change', function() {
    updateShownLock();
  });

  $('input[name=container]').on('change keydown keypress keyup mousedown click mouseup', function() {
      updateTargetContainer($(this).val());
  });

  $('#show-lock').on('click', showLockHandler);

  $('body').on('click', '.auth0-lock-close-button', function(ev) {
    ev.preventDefault();

    if($(this).parents('.output-box-result').length) {
      return;
    }

    showLockHandler();
  });

  $('body').on('keydown', function(ev) {
    if($('.auth0-lock-opened').length && ev.keyCode) {
      if($('.auth0-lock-opened').parents('.output-box-result').length) {
        return;
      }

      showLockHandler()
    }
  });
}

function updateShownLock() {
  updateLockInitializationCode();

  showLockHandler();
}

function showLockHandler(ev) {
    if(ev) {
      ev.preventDefault();
    }

    var method = $('[name="method"]').val();
    var clientID = $('[name="clientID"]').val();
    var domain = $('[name="domain"]').val();

    try {
      if ($('.auth0-lock').length) {
        window.lock.close();
      }

      window.lock = new Auth0LockPasswordless(clientID, domain);

      var options = getOptions();

      if(!ev) {
        options = getOptions('container');
      }

      // Execute Lock with options
      lock[method](options, function (err, profile, id_token, access_token, state, refresh_token) {
        showContainer(CONTAINERS.OUTPUT);
        $('#output code').removeClass('text-danger');
        $('#output code').text('');

        if (err) {
          $('#output code').removeClass('text-danger');
          $('#output code').text('Lock encountered an error' + (err.description ? ':\n' + err.description : '.'));
          return;
        }

        if (method === 'magiclink') {
          $('#output code').text('Email sent to ' + profile);
        } else {
          $('#output code').text('{\n  access_token: "' + access_token + '",\n  id_token: "' + id_token + '"\n}');
          hljs.highlightBlock(outputContainer.get(0));
        }
      });

      setTimeout(function () {
        remember.except('.auth0-lock-input');
      }, 0);

      if (options.container === currentLockContainerSelector) {
        showContainer(CONTAINERS.LOCK);
      }

    } catch (e) {
      $('#output code').text(e.message);
      $('#output code').addClass('text-danger');
      showContainer(CONTAINERS.OUTPUT);
    }
}

function showContainer (container) {
  switch (container) {
  case CONTAINERS.CODE: $('#output-tabs a[href="#lock-code-panel"]').tab('show'); break;
  case CONTAINERS.OUTPUT: $('#output-tabs a[href="#output-panel"]').tab('show'); break;
  case CONTAINERS.LOCK: $('#lock-container-box').show(); break;
  default: break;
  }
}

function updateTargetContainer (selector) {
  var sanitizedSelector = (selector ? selector.replace("#", "") : '') || 'container';
  $('.lock-container').prop('id', sanitizedSelector);
  $("#container-panel-title").text(sanitizedSelector);
  currentLockContainerSelector = sanitizedSelector;
}

function updateLockInitializationCode () {
   $('#lock-code code').text(getLockInitializationCode());
   hljs.highlightBlock($('#lock-code code').get(0));
}

function getLockInitializationCode () {
  var template = $('#lock-init-template').val();
  var templateValues = {};

  templateValues.options = JSON.stringify(getOptions());
  templateValues.method = $('[name="method"]').val();
  templateValues.clientID = $('[name="clientID"]').val();
  templateValues.domain = $('[name="domain"]').val();

  return Mustache.render(template, templateValues);
}

function getOptions (container) {
  var options = {};

  // Strings
  options.icon = $('[name="icon"]').val();
  options.container = container || ($('[name="container"]').val() || '').replace('#', '');
  options.defaultLocation = $('[name="defaultLocation"]').val();
  options.primaryColor = $('[name="primaryColor"]').val();
  options.callbackURL = $('[name="callbackURL"]').val() || undefined;
  options.responseType = $('[name="responseType"]').val() || undefined;

  // Booleans
  options.autoclose = !!$('[name="autoclose"]:checked').val();
  options.closable = !!$('[name="closable"]:checked').val();
  options.focusInput = !!$('[name="focusInput"]:checked').val();
  options.gravatar = !!$('[name="gravatar"]:checked').val();
  options.forceJSONP = !!$('[name="forceJSONP"]:checked').val();

  // Textareas + parsings
  try { options.dict = JSON.parse($('[name="dict"]').val()); } catch (e) {}
  try { options.authParams = JSON.parse($('[name="authParams"]').val() ); } catch (e) {}

  return options;
}

function renderAuthenticationSuccessMessage (authResponse) {
  var template = $('#authentication-success-template').val();
  var templateValues = {};

  templateValues.access_token = authResponse.access_token || '';
  templateValues.id_token = authResponse.id_token || '';
  templateValues.refresh_token = authResponse.refresh_token || '';
  templateValues.state = authResponse.state || '';
  templateValues.profile = JSON.stringify(authResponse.profile);

  $('#output code').text(Mustache.render(template, authResponse));
  hljs.highlightBlock($('#output code').get(0));

  showContainer(CONTAINERS.OUTPUT);
}

function tryDisplayAuthenticatedFeedback () {
  var clientID = $('[name="clientID"]').val();
  var domain = $('[name="domain"]').val();

  try {
    var lock = new Auth0LockPasswordless(clientID, domain);
    var response = lock.parseHash(window.location.hash);

    if (response.error) {
      return;
    }

    renderAuthenticationSuccessMessage(response);
  } catch (e) {
    // fail silently..
  }
}

$(function() {
  remember = require('remember')();

  bindEvents();
  updateLockInitializationCode();
  showContainer(CONTAINERS.CODE);
  showLockHandler();

  remember.except('input[name=container]');
  $("[rel=tooltip]").tooltip({ placement: 'right'});

  if (window.location.hash) {
    setTimeout(tryDisplayAuthenticatedFeedback, 500);
  }
});
<commit_msg>Now the toast is shown when the user authenticates<commit_after>var CONTAINERS = {
  LOCK: 1,
  CODE: 2,
  OUTPUT: 3
};

var currentLockContainerSelector;
var remember;

function bindEvents () {
  hljs.configure({
    classPrefix: ''
  });

  $('form input, form textarea').on('change keydown keypress keyup mousedown click mouseup', function() {
    updateShownLock();
  });

  $('form select').on('change', function() {
    updateShownLock();
  });

  $('input[name=container]').on('change keydown keypress keyup mousedown click mouseup', function() {
      updateTargetContainer($(this).val());
  });

  $('#show-lock').on('click', showLockHandler);

  $('body').on('click', '.auth0-lock-close-button', function(ev) {
    ev.preventDefault();

    if($(this).parents('.output-box-result').length) {
      return;
    }

    showLockHandler();
  });

  $('body').on('keydown', function(ev) {
    if($('.auth0-lock-opened').length && ev.keyCode) {
      if($('.auth0-lock-opened').parents('.output-box-result').length) {
        return;
      }

      showLockHandler();
    }
  });
}

function updateShownLock() {
  updateLockInitializationCode();

  showLockHandler();
}

function showLockHandler(ev) {
    if(ev) {
      ev.preventDefault();
    }

    var method = $('[name="method"]').val();
    var clientID = $('[name="clientID"]').val();
    var domain = $('[name="domain"]').val();

    try {
      if ($('.auth0-lock').length) {
        window.lock.close();
      }

      window.lock = new Auth0LockPasswordless(clientID, domain);

      var options = getOptions();

      if(!ev) {
        options = getOptions('container');
      }

      // Execute Lock with options
      lock[method](options, function (err, profile, id_token, access_token, state, refresh_token) {
        showContainer(CONTAINERS.OUTPUT);
        $('#output code').removeClass('text-danger');
        $('#output code').text('');

        if (err) {
          $('#output code').removeClass('text-danger');
          $('#output code').text('Lock encountered an error' + (err.description ? ':\n' + err.description : '.'));
          return;
        }

        if (method === 'magiclink') {
          $('#output code').text('Email sent to ' + profile);
        } else {
          $('#output code').text('{\n  access_token: "' + access_token + '",\n  id_token: "' + id_token + '"\n}');
          hljs.highlightBlock(outputContainer.get(0));
        }
      });

      setTimeout(function () {
        remember.except('.auth0-lock-input');
      }, 0);

      if (options.container === currentLockContainerSelector) {
        showContainer(CONTAINERS.LOCK);
      }

    } catch (e) {
      $('#output code').text(e.message);
      $('#output code').addClass('text-danger');
      showContainer(CONTAINERS.OUTPUT);
    }
}

function showContainer (container) {
  switch (container) {
  case CONTAINERS.CODE: $('#output-tabs a[href="#lock-code-panel"]').tab('show'); break;
  case CONTAINERS.OUTPUT: $('#output-tabs a[href="#output-panel"]').tab('show'); break;
  case CONTAINERS.LOCK: $('#lock-container-box').show(); break;
  default: break;
  }
}

function updateTargetContainer (selector) {
  var sanitizedSelector = (selector ? selector.replace("#", "") : '') || 'container';
  $('.lock-container').prop('id', sanitizedSelector);
  $("#container-panel-title").text(sanitizedSelector);
  currentLockContainerSelector = sanitizedSelector;
}

function updateLockInitializationCode () {
   $('#lock-code code').text(getLockInitializationCode());
   hljs.highlightBlock($('#lock-code code').get(0));
}

function getLockInitializationCode () {
  var template = $('#lock-init-template').val();
  var templateValues = {};

  templateValues.options = JSON.stringify(getOptions());
  templateValues.method = $('[name="method"]').val();
  templateValues.clientID = $('[name="clientID"]').val();
  templateValues.domain = $('[name="domain"]').val();

  return Mustache.render(template, templateValues);
}

function getOptions (container) {
  var options = {};

  // Strings
  options.icon = $('[name="icon"]').val();
  options.container = container || ($('[name="container"]').val() || '').replace('#', '');
  options.defaultLocation = $('[name="defaultLocation"]').val();
  options.primaryColor = $('[name="primaryColor"]').val();
  options.callbackURL = $('[name="callbackURL"]').val() || undefined;
  options.responseType = $('[name="responseType"]').val() || undefined;

  // Booleans
  options.autoclose = !!$('[name="autoclose"]:checked').val();
  options.closable = !!$('[name="closable"]:checked').val();
  options.focusInput = !!$('[name="focusInput"]:checked').val();
  options.gravatar = !!$('[name="gravatar"]:checked').val();
  options.forceJSONP = !!$('[name="forceJSONP"]:checked').val();

  // Textareas + parsings
  try { options.dict = JSON.parse($('[name="dict"]').val()); } catch (e) {}
  try { options.authParams = JSON.parse($('[name="authParams"]').val() ); } catch (e) {}

  return options;
}

function renderAuthenticationSuccessMessage (authResponse) {
  var template = $('#authentication-success-template').val();
  var templateValues = {};

  templateValues.access_token = authResponse.access_token || '';
  templateValues.id_token = authResponse.id_token || '';
  templateValues.refresh_token = authResponse.refresh_token || '';
  templateValues.state = authResponse.state || '';
  templateValues.profile = JSON.stringify(authResponse.profile);

  $('#output code').text(Mustache.render(template, authResponse));
  hljs.highlightBlock($('#output code').get(0));

  showContainer(CONTAINERS.OUTPUT);
}

function showToast() {
  $('.toast').addClass('is-visible');
}

function tryDisplayAuthenticatedFeedback () {
  var clientID = $('[name="clientID"]').val();
  var domain = $('[name="domain"]').val();

  try {
    var lock = new Auth0LockPasswordless(clientID, domain);
    var response = lock.parseHash(window.location.hash);

    if (response.error) {
      return;
    }

    renderAuthenticationSuccessMessage(response);
    showToast();
  } catch (e) {
    // fail silently..
  }
}

$(function() {
  remember = require('remember')();

  bindEvents();
  updateLockInitializationCode();
  showContainer(CONTAINERS.CODE);
  showLockHandler();

  remember.except('input[name=container]');
  $("[rel=tooltip]").tooltip({ placement: 'right'});

  if (window.location.hash) {
    setTimeout(tryDisplayAuthenticatedFeedback, 500);
  }
});
<|endoftext|>


<commit_before>/* globals describe it */

import * as assert from 'assert';
import { parse } from '../src/json';

const assertParse = (input) => {
  const { error, value } = parse(input);
  assert.strictEqual(error, null, `Error for input ${input}`);
  const expected = JSON.parse(input);
  assert.deepStrictEqual(value, expected, `No value for input ${input}`);
};

const assertFailsWithNoValue = (input) => {
  const { error, value } = parse(input);
  assert.ok(error, `No error for input ${input}`);
  assert.strictEqual(value, undefined, `Got value for input ${input}`);
};

const assertFailsWithRecovery = ([input, expected]) => {
  const { error, value } = parse(input);
  assert.ok(error, `For input ${input}`);
  assert.deepStrictEqual(value, expected, `For input ${input}`);
};

describe('json', () => {
  describe('parse is consistent with native JSON parse', () => {
    it('parses null', () => {
      ['null'].forEach(assertParse);
    });

    it('parses booleans', () => {
      ['true', 'false'].forEach(assertParse);
    });

    it('parses numbers', () => {
      [
        '0', '5', '50', '500', '5.00', '5.12', '0.12', '1E2', '1E20', '1E0', '1E-0', '-0', '-5',
        '-5.00', '-5.12', '-0.12', '-1E2', '-1E20', '-1E0', '-1E-0',
      ].forEach(assertParse);
    });

    it('parses strings', () => {
      ['"test"', '"\'"', '"\\""', '"\\\\"'].forEach(assertParse);
    });

    it('parses arrays', () => {
      [
        '[]', '[null]', '[true]', '["test"]', '[5]', '[[]]', '[{}]', '[1,2,3]',
      ].forEach(assertParse);
    });

    it('parses objects', () => {
      [
        '{}', '{ "test": null }', '{ "test": true }', '{ "test": "test" }', '{ "test": 5 }',
        '{ "a": 1, "b": 2, "c": 3 }', '{ "a": {} }',
      ].forEach(assertParse);
    });
  });

  describe('parse throws for', () => {
    it('invalid numbers', () => {
      ['00', '1E0.5', '-'].forEach(assertFailsWithNoValue);
    });

    it('invalid strings', () => {
      ['"\\\\""', '"test'].forEach(assertFailsWithNoValue);
    });
  });

  describe('parse throws for, but partially parses', () => {
    it('invalid arrays', () => {
      [
        ['[,]', []],
        ['[1,]', [1]],
        ['[1,2,]', [1, 2]],
        ['{ "test": [1,2,] }', { test: [1, 2] }],
      ].forEach(assertFailsWithRecovery);
    });

    it('invalid objects', () => {
      [
        ['{,}', {}],
        ['{ 5 }', {}],
        ['{ "a }', {}],
        ['{ "a" }', {}],
        ['{ "a": }', {}],
        ['{ "a": 5, }', { a: 5 }],
        ['{ "a": 5, " }', { a: 5 }],
        ['{ "a": 5 " }', { a: 5 }],
        ['{ "a": 5 5 }', { a: 5 }],
        ['{ "a": 5 : }', { a: 5 }],
        ['{ "a": 5, "b }', { a: 5 }],
        ['{ "a": 5, "b" }', { a: 5 }],
        ['{ "a": 5, "b": }', { a: 5 }],
        ['{ "a": 5, "b": 5, }', { a: 5, b: 5 }],
        ['[{ "a": 5, "b": 5, }]', [{ a: 5, b: 5 }]],
      ].forEach(assertFailsWithRecovery);
    });
  });
});
<commit_msg>Really important test<commit_after>/* globals describe it */

import * as assert from 'assert';
import { parse } from '../src/json';

const assertParse = (input) => {
  const { error, value } = parse(input);
  assert.strictEqual(error, null, `Error for input ${input}`);
  const expected = JSON.parse(input);
  assert.deepStrictEqual(value, expected, `No value for input ${input}`);
};

const assertFailsWithNoValue = (input) => {
  const { error, value } = parse(input);
  assert.ok(error, `No error for input ${input}`);
  assert.strictEqual(value, undefined, `Got value for input ${input}`);
};

const assertFailsWithRecovery = ([input, expected]) => {
  const { error, value } = parse(input);
  assert.ok(error, `For input ${input}`);
  assert.deepStrictEqual(value, expected, `For input ${input}`);
};

describe('json', () => {
  describe('parse is consistent with native JSON parse', () => {
    it('parses null', () => {
      ['null'].forEach(assertParse);
    });

    it('parses booleans', () => {
      ['true', 'false'].forEach(assertParse);
    });

    it('parses numbers', () => {
      [
        '0', '5', '50', '500', '5.00', '5.12', '0.12', '1E2', '1E20', '1E0', '1E-0', '-0', '-5',
        '-5.00', '-5.12', '-0.12', '-1E2', '-1E20', '-1E0', '-1E-0',
      ].forEach(assertParse);
    });

    it('parses strings', () => {
      ['"test"', '"\'"', '"\\""', '"\\\\"'].forEach(assertParse);
    });

    it('parses arrays', () => {
      [
        '[]', '[null]', '[true]', '["test"]', '[5]', '[[]]', '[{}]', '[1,2,3]',
      ].forEach(assertParse);
    });

    it('parses objects', () => {
      [
        '{}', '{ "test": null }', '{ "test": true }', '{ "test": "test" }', '{ "test": 5 }',
        '{ "a": 1, "b": 2, "c": 3 }', '{ "a": {} }',
      ].forEach(assertParse);
    });
  });

  describe('parse throws for', () => {
    it('invalid numbers', () => {
      ['00', '1E0.5', '-'].forEach(assertFailsWithNoValue);
    });

    it('invalid strings', () => {
      ['"\\\\""', '"test'].forEach(assertFailsWithNoValue);
    });
  });

  describe('parse throws for, but partially parses', () => {
    it('invalid arrays', () => {
      [
        ['[,]', []],
        ['[1,]', [1]],
        ['[1,2,]', [1, 2]],
        ['{ "test": [1,2,] }', { test: [1, 2] }],
      ].forEach(assertFailsWithRecovery);
    });

    it('invalid objects', () => {
      [
        ['{,}', {}],
        ['{ 5 }', {}],
        ['{ "a }', {}],
        ['{ "a" }', {}],
        ['{ "a": }', {}],
        ['{ "a" 5 }', {}],
        ['{ "a": 5, }', { a: 5 }],
        ['{ "a": 5, " }', { a: 5 }],
        ['{ "a": 5 " }', { a: 5 }],
        ['{ "a": 5 5 }', { a: 5 }],
        ['{ "a": 5 : }', { a: 5 }],
        ['{ "a": 5, "b }', { a: 5 }],
        ['{ "a": 5, "b" }', { a: 5 }],
        ['{ "a": 5, "b": }', { a: 5 }],
        ['{ "a": 5, "b": 5, }', { a: 5, b: 5 }],
        ['[{ "a": 5, "b": 5, }]', [{ a: 5, b: 5 }]],
      ].forEach(assertFailsWithRecovery);
    });
  });
});
<|endoftext|>


<commit_before>"use strict";
/*global describe*/ // , it, assert*/

describe("like", function () {
});
<commit_msg>Like unit testing<commit_after>"use strict";
/*global describe*/ // , it, assert*/

describe("like", function () {

    var
        string = "Hello World!",
        object = {
            "number": 1,
            "string": string,
            "null": null,
            "object": {member: "value"},
            "function": function () {
                return string;
            }
        },
        object2 = gpf.extend({
            cloneOf: object
        }, object);

    describe("gpf.like", function () {

        it("supports basic comparisons", function () {
            assert(true === gpf.like(1, 1));
            assert(false === gpf.like(1, new Number(1)));
            assert(false === gpf.like(1, 2));
            assert(true === gpf.like(1, 1.0));
            assert(true === gpf.like("abc", "abc"));
            assert(false === gpf.like("abc", new String("abc")));
            assert(false === gpf.like("abc", "abcd"));
            assert(true === gpf.like(object, object));
        });

        it("tolerates alike comparison", function () {
            assert(true === gpf.like(1, new Number(1), true));
            assert(false === gpf.like("1", new Number(1), true));
            assert(true === gpf.like("abc", new String("abc"), true));
            assert(false === gpf.like(0, new String("0"), true));
        });

        it("tolerates deep comparison", function () {
            assert(true === gpf.like(object, gpf.extend({}, object)));
            assert(true === gpf.like(object2, gpf.extend({}, object2)));
        });

        it("supports complex deep comparison");

    });

});
<|endoftext|>


<commit_before>var WebKit = require('../');
var expect = require('expect.js');
var fs = require('fs');

describe("load method", function suite() {
	it("should accept no arguments", function(done) {
		WebKit.load("", null, function(err, w) {
			done();
		});
	});

	it("should load html content", function(done) {
		WebKit.load("http://localhost", {content: '
test
'}).on('ready', function() {
			this.html(function(err, str) {
				expect(err).to.not.be.ok();
				expect(str).to.be("
test
");
				done();
			});
		});
	});

	it("should callback with error when url cannot be resolved", function(done) {
		this.timeout(10000);
		WebKit.load("http://atipepipapa-sdqdqsd.com", function(err) {
			expect(err).to.be.ok();
			done();
		});
	});

	it("should 404", function(done) {
		WebKit.load("http://google.com/sdfsdfsdf", function(err) {
			expect(err).to.be(404);
			done();
		});
	});

	it("should allow to load another uri just after", function(done) {
		this.timeout(5000);
		WebKit.load('http://google.com', function(err, w) {
			w.load('http://geoip.edagames.com')
			.once('response', function(res) {
				res.data(function(err, data) {
					expect(JSON.parse(data.toString()).country).to.be.ok();
					done();
				});
			});
		});
	});

	it("should time out before loading started", function(done) {
		this.timeout(500);
		WebKit.load('http://google.com', {timeout:5}, function(err, w) {
			expect(err).to.be.ok();
			expect(w.status).to.be(0);
			done();
		});
	});

	it("should time out after loading started", function(done) {
		this.timeout(5000);
		WebKit.load('https://linkedin.com', {timeout:200}, function(err, w) {
			expect(err).to.be.ok();
			expect(w.status).to.be(0);
			done();
		});
	});

	it("should time out then unload", function(done) {
		this.timeout(5000);
		WebKit.load('http://google.com', {timeout:50}, function(err, w) {
			expect(err).to.be.ok();
			expect(w.status).to.be(0);
			w.unload(function(err) {
				expect(err).to.not.be.ok();
				done();
			});
		});
	});

	it("should stop after a stop call", function(done) {
		this.timeout(10000);

		WebKit(function(err, w) {
			w.load('http://google.com');
			setImmediate(function() {
				w.stop(function(err, wasLoading) {
					expect(w.readyState).to.be('stop');
					expect(err).to.not.be.ok();
					expect(wasLoading).to.be(true);
					done();
				});
			});
		});

		// meaning of this ?
		/*
		w.once('idle', function() {
			setTimeout(function() {
				w.stop(function(err, wasLoading) {
					expect(err).to.not.be.ok();
					expect(wasLoading).to.be(false);
					done();
				});
			}, 1000);
		});
		*/
	});

	it("should fail gracefully", function(done) {
		var server = require('http').createServer(function(req, res) {
			res.statusCode = 501;
			res.end("fail");
		}).listen(function() {
			WebKit.load("http://localhost:" + server.address().port, function(err, w) {
				expect(err).to.be(501);
				setImmediate(function() {
					server.close();
					done();
				});
			});
		});
	});

	it("should fail gracefully even with a timeout", function(done) {
		var server = require('http').createServer(function(req, res) {
			setTimeout(function() {
				res.statusCode = 501;
				res.end("fail");
			}, 1000);
		}).listen(function() {
			WebKit.load("http://localhost:" + server.address().port, {timeout: 500}, function(err, w) {
				expect(err).not.to.be(501);
				w.stop(function(err, wasLoading) {
					expect(err).to.not.be.ok();
					expect(wasLoading).to.be(true);
				});
				setTimeout(function() {
					server.close();
					done();
				}, 1000);
			});
		});
	});

	it("should fail to load immediately", function(done) {
		// for super weird reasons this test fails because of the particular
		// way the url is crafted (length of each component is critical).
		// it won't fail after 8745c188, though
		WebKit.load('http://localhost:16724/aaaaa/bbbbb?cccc=c', function(err) {
			expect(err).to.be.ok();
			done();
		});
	});

	it("should be able to load twice in a row", function(done) {
		this.timeout(10000);
		WebKit.load('http://google.com', function(err, w) {
			w.load('http://google.com', function(err) {
				expect(err).to.not.be.ok();
				done();
			});
		});
	});

	it("should be able to fail then load", function(done) {
		this.timeout(10000);
		WebKit.load('http://google.com/azertyuiop404', function(err, w) {
			expect(err).to.be(404);
			w.load('http://google.com', function(err) {
				expect(err).to.not.be.ok();
				done();
			});
		});
	});

	it("should be able to load a url with a default protocol", function(done) {
		this.timeout(4000);
		WebKit.load('www.debian.org', function(err) {
			expect(err).to.not.be.ok();
			done();
		});
	});
});
<commit_msg>test/load: use a safer remote url<commit_after>var WebKit = require('../');
var expect = require('expect.js');
var fs = require('fs');

describe("load method", function suite() {
	it("should accept no arguments", function(done) {
		WebKit.load("", null, function(err, w) {
			done();
		});
	});

	it("should load html content", function(done) {
		WebKit.load("http://localhost", {content: '
test
'}).on('ready', function() {
			this.html(function(err, str) {
				expect(err).to.not.be.ok();
				expect(str).to.be("
test
");
				done();
			});
		});
	});

	it("should callback with error when url cannot be resolved", function(done) {
		this.timeout(10000);
		WebKit.load("http://atipepipapa-sdqdqsd.com", function(err) {
			expect(err).to.be.ok();
			done();
		});
	});

	it("should 404", function(done) {
		WebKit.load("http://google.com/sdfsdfsdf", function(err) {
			expect(err).to.be(404);
			done();
		});
	});

	it("should allow to load another uri just after", function(done) {
		this.timeout(5000);
		WebKit.load('http://google.com', function(err, w) {
			w.load('https://github.com')
			.once('response', function(res) {
				res.data(function(err, data) {
					expect(data.length).to.be.greaterThan(50000);
					done();
				});
			});
		});
	});

	it("should time out before loading started", function(done) {
		this.timeout(500);
		WebKit.load('http://google.com', {timeout:5}, function(err, w) {
			expect(err).to.be.ok();
			expect(w.status).to.be(0);
			done();
		});
	});

	it("should time out after loading started", function(done) {
		this.timeout(5000);
		WebKit.load('https://linkedin.com', {timeout:200}, function(err, w) {
			expect(err).to.be.ok();
			expect(w.status).to.be(0);
			done();
		});
	});

	it("should time out then unload", function(done) {
		this.timeout(5000);
		WebKit.load('http://google.com', {timeout:50}, function(err, w) {
			expect(err).to.be.ok();
			expect(w.status).to.be(0);
			w.unload(function(err) {
				expect(err).to.not.be.ok();
				done();
			});
		});
	});

	it("should stop after a stop call", function(done) {
		this.timeout(10000);

		WebKit(function(err, w) {
			w.load('http://google.com');
			setImmediate(function() {
				w.stop(function(err, wasLoading) {
					expect(w.readyState).to.be('stop');
					expect(err).to.not.be.ok();
					expect(wasLoading).to.be(true);
					done();
				});
			});
		});

		// meaning of this ?
		/*
		w.once('idle', function() {
			setTimeout(function() {
				w.stop(function(err, wasLoading) {
					expect(err).to.not.be.ok();
					expect(wasLoading).to.be(false);
					done();
				});
			}, 1000);
		});
		*/
	});

	it("should fail gracefully", function(done) {
		var server = require('http').createServer(function(req, res) {
			res.statusCode = 501;
			res.end("fail");
		}).listen(function() {
			WebKit.load("http://localhost:" + server.address().port, function(err, w) {
				expect(err).to.be(501);
				setImmediate(function() {
					server.close();
					done();
				});
			});
		});
	});

	it("should fail gracefully even with a timeout", function(done) {
		var server = require('http').createServer(function(req, res) {
			setTimeout(function() {
				res.statusCode = 501;
				res.end("fail");
			}, 1000);
		}).listen(function() {
			WebKit.load("http://localhost:" + server.address().port, {timeout: 500}, function(err, w) {
				expect(err).not.to.be(501);
				w.stop(function(err, wasLoading) {
					expect(err).to.not.be.ok();
					expect(wasLoading).to.be(true);
				});
				setTimeout(function() {
					server.close();
					done();
				}, 1000);
			});
		});
	});

	it("should fail to load immediately", function(done) {
		// for super weird reasons this test fails because of the particular
		// way the url is crafted (length of each component is critical).
		// it won't fail after 8745c188, though
		WebKit.load('http://localhost:16724/aaaaa/bbbbb?cccc=c', function(err) {
			expect(err).to.be.ok();
			done();
		});
	});

	it("should be able to load twice in a row", function(done) {
		this.timeout(10000);
		WebKit.load('http://google.com', function(err, w) {
			w.load('http://google.com', function(err) {
				expect(err).to.not.be.ok();
				done();
			});
		});
	});

	it("should be able to fail then load", function(done) {
		this.timeout(10000);
		WebKit.load('http://google.com/azertyuiop404', function(err, w) {
			expect(err).to.be(404);
			w.load('http://google.com', function(err) {
				expect(err).to.not.be.ok();
				done();
			});
		});
	});

	it("should be able to load a url with a default protocol", function(done) {
		this.timeout(4000);
		WebKit.load('www.debian.org', function(err) {
			expect(err).to.not.be.ok();
			done();
		});
	});
});
<|endoftext|>


<commit_before>module( "load", { teardown: moduleTeardown } );

asyncTest( "jar.load - js", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.js";

    jar( "jar.load - js" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "js", "jar.load - js" ).done(function( data, base ) {
                ok( data.length, "Data is returned" );
                ok( js, "Variable is assigned" );
                ok( base instanceof jar, "Second argument is instace of jar" );

                // cleanup
                window.js = undefined;

                // wait a bit, so data can be writed
                window.setTimeout(function() {

                    ok( jar.has( "jar.load - js", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "js", "jar.load - js" ).done(function( data, base ) {
                        ok( data.length, "Data is returned" );
                        ok( js, "Variable is assigned" );
                        ok( base instanceof jar, "Second argument is instace of jar" );

                        // cleanup
                        window.js = undefined;

                        start();
                    });
                }, 100 );
            });
        });
    });
});

asyncTest( "jar.load - xml", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.xml";

    jar( "jar.load - xml" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "xml", "jar.load - xml" ).done(function( data, base ) {
                strictEqual( jar.type( data ), "xml", "Data is returned" );
                ok( base instanceof jar, "Second argument is instace of jar" );

                // wait a bit, so data can be writed
                window.setTimeout(function() {

                    ok( jar.has( "jar.load - xml", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "xml", "jar.load - xml" ).done(function( data, base ) {
                        strictEqual( jar.type( data ), "xml", "Data is returned" );
                        ok( base instanceof jar, "Second argument is instace of jar" );

                        start();
                    });
                }, 100 );
            });
        });
    });
});

asyncTest( "jar.load - css", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.css";

    jar( "jar.load - css" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "css", "jar.load - css" ).done(function( data, base ) {
                var element = jQuery( '

' ).appendTo( "#qunit-fixture" );
                strictEqual( element.css( "font-size" ), "99px", "css style should be applied" );

                ok( base instanceof jar, "Second argument is instace of jar" );

                // wait a bit, so data can be writed
                window.setTimeout(function() {

                    ok( jar.has( "jar.load - css", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "css", "jar.load - css" ).done(function( data, base ) {
                        ok( base instanceof jar, "Second argument is instace of jar" );

                        start();
                    });
                }, 100 );
            });
        });
    });
});<commit_msg>Remove empty lines<commit_after>module( "load", { teardown: moduleTeardown } );

asyncTest( "jar.load - js", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.js";

    jar( "jar.load - js" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "js", "jar.load - js" ).done(function( data, base ) {
                ok( data.length, "Data is returned" );
                ok( js, "Variable is assigned" );
                ok( base instanceof jar, "Second argument is instace of jar" );

                // cleanup
                window.js = undefined;

                // wait a bit, so data can be writed
                window.setTimeout(function() {
                    ok( jar.has( "jar.load - js", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "js", "jar.load - js" ).done(function( data, base ) {
                        ok( data.length, "Data is returned" );
                        ok( js, "Variable is assigned" );
                        ok( base instanceof jar, "Second argument is instace of jar" );

                        // cleanup
                        window.js = undefined;

                        start();
                    });
                }, 100 );
            });
        });
    });
});

asyncTest( "jar.load - xml", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.xml";

    jar( "jar.load - xml" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "xml", "jar.load - xml" ).done(function( data, base ) {
                strictEqual( jar.type( data ), "xml", "Data is returned" );
                ok( base instanceof jar, "Second argument is instace of jar" );

                // wait a bit, so data can be writed
                window.setTimeout(function() {
                    ok( jar.has( "jar.load - xml", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "xml", "jar.load - xml" ).done(function( data, base ) {
                        strictEqual( jar.type( data ), "xml", "Data is returned" );
                        ok( base instanceof jar, "Second argument is instace of jar" );

                        start();
                    });
                }, 100 );
            });
        });
    });
});

asyncTest( "jar.load - css", function() {
    var path = "//" + window.location.host + window.location.pathname + "data/data.css";

    jar( "jar.load - css" ).done(function() {
        this.clear().done(function() {

            // through xhr-request
            jar.load( path, "css", "jar.load - css" ).done(function( data, base ) {
                var element = jQuery( '

' ).appendTo( "#qunit-fixture" );
                strictEqual( element.css( "font-size" ), "99px", "css style should be applied" );

                ok( base instanceof jar, "Second argument is instace of jar" );

                // wait a bit, so data can be writed
                window.setTimeout(function() {
                    ok( jar.has( "jar.load - css", path ), "Meta-data should be intializated" );

                    // through jar-store
                    jar.load( path, "css", "jar.load - css" ).done(function( data, base ) {
                        ok( base instanceof jar, "Second argument is instace of jar" );

                        start();
                    });
                }, 100 );
            });
        });
    });
});<|endoftext|>


<commit_before>var assert = require('assert'),
    main;

function mockConsole() {
    return {
        warnings: [],
        warn: function(str) {
            this.warnings.push(str);
        },
        loggings: [],
        log: function(str) {
            this.loggings.push(str);
        }
    };
}

function mockProcess() {
    var p = {
        argv: ['jslint'],
        exit: function (c) {
            this.exitCode = c;
            this.events.exit.forEach(function (f) {
                f();
            });
        },
        doDrain: function() {
            this.events.drain.forEach(function (f) {
                f();
            });
        },
        events: { exit: [],
                  drain: [] },
        on: function (event,f) {
            this.events[event].push(f);
        },
        stdout: {
            isTTY: true,

            /* mock: call callback right away */
            on: function (event, fn) {
                fn();
                p.doDrain()
            },
            callbacks: {
                drain: []
            }
        }
    };
    return p;
}

function mockParsed() {
    return {
        argv: {
            remain: []
        }
    };
}

suite('jslint main', function () {
    var pro, con;

    setup(function () {
        main = require('../lib/main');

        con = mockConsole();
        pro = mockProcess();

        main.setConsole(con);
        main.setProcess(pro);
    });

    test('main - no args', function () {
        var parsed = mockParsed();

        main.main(parsed);

        assert.ok(main);
        assert.strictEqual(1, pro.exitCode);
        assert.strictEqual(2, con.warnings.length);
    });

    test('main - three files', function (done) {
        var parsed = mockParsed();

        parsed.argv.remain.push('lib/main.js');
        parsed.argv.remain.push('lib/main.js');
        parsed.argv.remain.push('lib/main.js');

        pro.on('exit', done);

        parsed.terse = true;

        main.main(parsed);

        assert.ok(main);
    });

    test('main - one file, not tty, json output', function (done) {
        var parsed = mockParsed();

        parsed.argv.remain.push('lib/main.js');

        parsed.json = true;

        pro.stdout.isTTY = false;

        pro.on('drain', function () {
            assert.strictEqual(0, pro.exitCode);
            done();
        });

        main.main(parsed);

        assert.ok(main);

        // expect process.exit(0) to be as yet uncalled
        assert.strictEqual(undefined, pro.exitCode);
    });

    test('todo in command-line options', function () {
        var o = main.commandOptions();

        assert.strictEqual(Boolean, o.todo);
    });
});
<commit_msg>add unit tests for jslintrc.example<commit_after>var assert = require('assert'),
    main;

function mockConsole() {
    return {
        warnings: [],
        warn: function(str) {
            this.warnings.push(str);
        },
        loggings: [],
        log: function(str) {
            this.loggings.push(str);
        }
    };
}

function mockProcess() {
    var p = {
        argv: ['jslint'],
        exit: function (c) {
            this.exitCode = c;
            this.events.exit.forEach(function (f) {
                f();
            });
        },
        doDrain: function() {
            this.events.drain.forEach(function (f) {
                f();
            });
        },
        events: { exit: [],
                  drain: [] },
        on: function (event,f) {
            this.events[event].push(f);
        },
        stdout: {
            isTTY: true,

            /* mock: call callback right away */
            on: function (event, fn) {
                fn();
                p.doDrain()
            },
            callbacks: {
                drain: []
            }
        }
    };
    return p;
}

function mockParsed() {
    return {
        argv: {
            remain: []
        }
    };
}

suite('jslint main', function () {
    var pro, con;

    setup(function () {
        main = require('../lib/main');

        con = mockConsole();
        pro = mockProcess();

        main.setConsole(con);
        main.setProcess(pro);
    });

    test('main - no args', function () {
        var parsed = mockParsed();

        main.main(parsed);

        assert.ok(main);
        assert.strictEqual(1, pro.exitCode);
        assert.strictEqual(2, con.warnings.length);
    });

    test('main - three files', function (done) {
        var parsed = mockParsed();

        parsed.argv.remain.push('lib/main.js');
        parsed.argv.remain.push('lib/main.js');
        parsed.argv.remain.push('lib/main.js');

        pro.on('exit', done);

        parsed.terse = true;

        main.main(parsed);

        assert.ok(main);
    });

    test('main - one file, not tty, json output', function (done) {
        var parsed = mockParsed();

        parsed.argv.remain.push('lib/main.js');

        parsed.json = true;

        pro.stdout.isTTY = false;

        pro.on('drain', function () {
            assert.strictEqual(0, pro.exitCode);
            done();
        });

        main.main(parsed);

        assert.ok(main);

        // expect process.exit(0) to be as yet uncalled
        assert.strictEqual(undefined, pro.exitCode);
    });

    test('todo in command-line options', function () {
        var o = main.commandOptions();

        assert.strictEqual(Boolean, o.todo);
    });

    function isBasicType(type, value) {
        return type(value).valueOf() === value;
    }

    test('isBasicType works', function () {

        assert.ok(isBasicType(Boolean, true));
        assert.ok(isBasicType(Boolean, false));
        assert.ok(isBasicType(Number, 1));

        assert.ok(!isBasicType(Boolean, 0));
        assert.ok(!isBasicType(Boolean, 1));
        assert.ok(!isBasicType(Number, false));
        assert.ok(!isBasicType(String, 1));
        assert.ok(!isBasicType(Number, '1'));
    });

    test('example jslintrc contains only valid options', function (done) {

        var options = main.commandOptions(),
            fs = require('fs');

        fs.readFile("jslintrc.example", function (err, file) {
            if (err) {
                throw err;
            }

            var example = JSON.parse(file),
                keys = Object.keys(example);

            keys.forEach(function(opt) {
                assert.ok(options.hasOwnProperty(opt));

                var type = options[opt],
                    value = example[opt];

                assert.ok(isBasicType(type, value));
            });

            done();
        });
    });

});
<|endoftext|>


<commit_before>/* globals describe it beforeEach */
'use strict'

const chai = require('chai')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')

const expect = chai.expect
chai.use(sinonChai)

describe('main', function () {
  let stubs
  let getUrl
  let git
  let github
  let logger
  let parseArguments

  beforeEach('create stubs', function () {
    getUrl = sinon.stub().returns('some url')
    git = {
      getSemverTags: sinon.stub(),
      getMergeCommits: sinon.stub(),
      getPRs: sinon.stub()
    }
    github = {}
    logger = {
      debug: sinon.spy(),
      info: sinon.spy(),
      error: sinon.spy()
    }
    parseArguments = sinon.stub()
    stubs = {}
    stubs[require.resolve('../lib/arguments')] = {
      parseArguments
    }
    stubs[require.resolve('../lib/git')] = git
    stubs[require.resolve('../lib/github')] = github
    stubs[require.resolve('../lib/logging')] = {
      logger
    }
    stubs[require.resolve('../lib/util')] = {
      getUrl
    }
  })

  it('returns when no tags are found in repository', function (done) {
    git.getSemverTags.returns([])
    parseArguments.returns({logLevel: 'debug'})
    const main = requireInject('../lib/main', stubs)
    main().then(function (retcode) {
      expect(retcode).to.equal(1)
      expect(logger.error).to.have.been.calledWith('No tags found in repository')
      done()
    })
  })

  it('returns when tag is not semver compliant', function () {
    git.getSemverTags.returns(['a tag', 'another tag'])
    const tag = 'not a semver tag'
    parseArguments.returns({
      logLevel: 'debug',
      tag
    })
    const main = requireInject('../lib/main', stubs)
    main().then(function (retcode) {
      expect(retcode).to.equal(1)
      expect(logger.error).to.have.been.calledWith(
        'Tag not semver compliant: %s', tag)
    })
  })

  it('returns when tag is not found in repository', function () {
    git.getSemverTags.returns(['v1.0.0'])
    const tag = 'v0.1.0'
    parseArguments.returns({
      logLevel: 'debug',
      tag
    })
    const main = requireInject('../lib/main', stubs)
    main().then(function (retcode) {
      expect(retcode).to.equal(1)
      expect(logger.error).to.have.been.calledWith(
        'Tag not found in repository: %s', tag)
    })
  })

  it('writes done to log on success', function (done) {
    git.getSemverTags.returns(['v1.0.0'])
    git.getMergeCommits.returns(['a commit', 'another commit'])
    git.getPRs(['a PR', 'another PR'])
    const tag = 'v1.0.0'
    parseArguments.returns({
      logLevel: 'debug',
      tag
    })
    github.authorize = function () {
      return Promise.resolve('authorization data')
    }
    github.writeComments = function () {
      return Promise.resolve('prs with comments')
    }
    const main = requireInject('../lib/main', stubs)
    main().then(function (retcode) {
      expect(retcode).to.equal(0)
      expect(logger.info).to.have.been.calledWith('Done!')
      done()
    })
  })

  it('writes unexpected error to log on failure', function (done) {
    git.getSemverTags.returns(['v1.0.0', 'v0.0.1'])
    git.getMergeCommits.returns(['a commit', 'another commit'])
    git.getPRs(['a PR', 'another PR'])
    const tag = 'v1.0.0'
    parseArguments.returns({
      logLevel: 'debug',
      tag
    })
    github.authorize = function () {
      return Promise.resolve('authorization data')
    }
    const error = 'some error'
    github.writeComments = function () {
      return Promise.reject(error)
    }
    const main = requireInject('../lib/main', stubs)
    main().then(function (retcode) {
      expect(retcode).to.equal(1)
      expect(logger.error).to.have.been.calledWith(
        'Unexpected error: %s', error)
      done()
    })
  })
})
<commit_msg>Update test to check number of comments written is logged<commit_after>/* globals describe it beforeEach */
'use strict'

const chai = require('chai')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')

const expect = chai.expect
chai.use(sinonChai)

describe('main', function () {
  let stubs
  let getUrl
  let git
  let github
  let logger
  let parseArguments

  beforeEach('create stubs', function () {
    getUrl = sinon.stub().returns('some url')
    git = {
      getSemverTags: sinon.stub(),
      getMergeCommits: sinon.stub(),
      getPRs: sinon.stub()
    }
    github = {}
    logger = {
      debug: sinon.spy(),
      info: sinon.spy(),
      error: sinon.spy()
    }
    parseArguments = sinon.stub()
    stubs = {}
    stubs[require.resolve('../lib/arguments')] = {
      parseArguments
    }
    stubs[require.resolve('../lib/git')] = git
    stubs[require.resolve('../lib/github')] = github
    stubs[require.resolve('../lib/logging')] = {
      logger
    }
    stubs[require.resolve('../lib/util')] = {
      getUrl
    }
  })

  it('returns when no tags are found in repository', function (done) {
    git.getSemverTags.returns([])
    parseArguments.returns({logLevel: 'debug'})
    const main = requireInject('../lib/main', stubs)
    main().then(function (retcode) {
      expect(retcode).to.equal(1)
      expect(logger.error).to.have.been.calledWith('No tags found in repository')
      done()
    })
  })

  it('returns when tag is not semver compliant', function () {
    git.getSemverTags.returns(['a tag', 'another tag'])
    const tag = 'not a semver tag'
    parseArguments.returns({
      logLevel: 'debug',
      tag
    })
    const main = requireInject('../lib/main', stubs)
    main().then(function (retcode) {
      expect(retcode).to.equal(1)
      expect(logger.error).to.have.been.calledWith(
        'Tag not semver compliant: %s', tag)
    })
  })

  it('returns when tag is not found in repository', function () {
    git.getSemverTags.returns(['v1.0.0'])
    const tag = 'v0.1.0'
    parseArguments.returns({
      logLevel: 'debug',
      tag
    })
    const main = requireInject('../lib/main', stubs)
    main().then(function (retcode) {
      expect(retcode).to.equal(1)
      expect(logger.error).to.have.been.calledWith(
        'Tag not found in repository: %s', tag)
    })
  })

  it('logs number of comments written on success', function (done) {
    git.getSemverTags.returns(['v1.0.0'])
    git.getMergeCommits.returns(['a commit', 'another commit'])
    git.getPRs(['a PR', 'another PR'])
    const tag = 'v1.0.0'
    parseArguments.returns({
      logLevel: 'debug',
      tag
    })
    github.authorize = function () {
      return Promise.resolve('authorization data')
    }
    const newComments = ['a new comment', null, 'another new comment']
    github.writeComments = function () {
      return Promise.resolve(newComments)
    }
    const main = requireInject('../lib/main', stubs)
    main().then(function (retcode) {
      expect(retcode).to.equal(0)
      expect(logger.info).to.have.been.calledWith('%d comments written', 2)
      expect(logger.info).to.have.been.calledWith('Done!')
      done()
    })
  })

  it('writes unexpected error to log on failure', function (done) {
    git.getSemverTags.returns(['v1.0.0', 'v0.0.1'])
    git.getMergeCommits.returns(['a commit', 'another commit'])
    git.getPRs(['a PR', 'another PR'])
    const tag = 'v1.0.0'
    parseArguments.returns({
      logLevel: 'debug',
      tag
    })
    github.authorize = function () {
      return Promise.resolve('authorization data')
    }
    const error = 'some error'
    github.writeComments = function () {
      return Promise.reject(error)
    }
    const main = requireInject('../lib/main', stubs)
    main().then(function (retcode) {
      expect(retcode).to.equal(1)
      expect(logger.error).to.have.been.calledWith(
        'Unexpected error: %s', error)
      done()
    })
  })
})
<|endoftext|>


<commit_before>var Window        = require('pex-sys/Window');
var Draw          = require('pex-draw');
var glslify       = require('./local_modules/glslify-sync');
var PerspCamera   = require('pex-cam/PerspCamera');
var Arcball       = require('pex-cam/Arcball');
var GUI           = require('pex-gui');
var debug         = require('debug').enable('*');
var log           = require('debug')('main');
var loadGLTF      = require('../');
var isBrowser     = require('is-browser');
var Vec3          = require('pex-math/Vec3');

var ASSETS_DIR    = isBrowser ? 'assets' : __dirname + '/assets';

Window.create({
    settings: {
        width: 1280,
        height: 720
    },
    resourcesRaw: {
        showColorsVert    : { text : glslify(__dirname + '/assets/glsl/ShowColors.vert')},
        showColorsFrag    : { text : glslify(__dirname + '/assets/glsl/ShowColors.frag')},
        solidColorVert    : { text : glslify(__dirname + '/assets/glsl/SolidColor.vert')},
        solidColorFrag    : { text : glslify(__dirname + '/assets/glsl/SolidColor.frag')},
        showNormalsVert   : { text : glslify(__dirname + '/assets/glsl/ShowNormals.vert')},
        showNormalsFrag   : { text : glslify(__dirname + '/assets/glsl/ShowNormals.frag')},
        showTexCoordsVert : { text : glslify(__dirname + '/assets/glsl/ShowTexCoords.vert')},
        showTexCoordsFrag : { text : glslify(__dirname + '/assets/glsl/ShowTexCoords.frag')}
    },
    init: function() {
        var ctx = this.getContext();
        this.debugDraw = new Draw(ctx);

        this.gui = new GUI(ctx, this.getWidth(), this.getHeight());
        this.gui.addHeader('Settings');

        this.camera  = new PerspCamera(45, this.getAspectRatio(), 0.01, 20.0);
        this.camera.lookAt([0, 2, 2], [0, 0, 0], [0, 1, 0]);
        ctx.setProjectionMatrix(this.camera.getProjectionMatrix());
        ctx.setViewMatrix(this.camera.getViewMatrix());

        this.arcball = new Arcball(this.camera, this.getWidth(), this.getHeight());
        this.arcball.setRadiusScale(1.5);
        this.arcball.setSpeed(1);
        this.addEventListener(this.arcball);

        this.showColorsProgram = ctx.createProgram(this.resourcesRaw.showColorsVert.text, this.resourcesRaw.showColorsFrag.text);
        this.solidColorProgram = ctx.createProgram(this.resourcesRaw.solidColorVert.text, this.resourcesRaw.solidColorFrag.text);
        this.showNormals = ctx.createProgram(this.resourcesRaw.showNormalsVert.text, this.resourcesRaw.showNormalsFrag.text);
        this.showTexCoords = ctx.createProgram(this.resourcesRaw.showTexCoordsVert.text, this.resourcesRaw.showTexCoordsFrag.text);

        loadGLTF(ctx, ASSETS_DIR + '/models/duck/duck.gltf', function(err, scene) {
            if (err) {
                log('loadGLTF done', err);
                return;
            }
            log('loadGLTF done');

            this.scene = scene;
        }.bind(this));
    },
    draw: function() {
        var ctx = this.getContext();

        ctx.setClearColor(0.1, 0.1, 0.1, 1.0);
        ctx.clear(ctx.COLOR_BIT | ctx.DEPTH_BIT);
        ctx.setDepthTest(true);

        this.arcball.apply();
        ctx.setViewMatrix(this.camera.getViewMatrix());
        ctx.setLineWidth(2);

        ctx.bindProgram(this.showColorsProgram);
        this.debugDraw.drawPivotAxes(0.5);
        this.debugDraw.setColor([0.5, 0.5, 0.5, 1.0]);
        this.debugDraw.drawGrid([5, 5], 10);

        ctx.bindProgram(this.showNormals);
        this.showNormals.setUniform('uPointSize', 20);
        //ctx.bindProgram(this.showTexCoords);
        //this.showTexCoords.setUniform('uPointSize', 20);
        //ctx.bindProgram(this.showNormals);
        //this.solidColorProgram.setUniform('uColor', [1, 0, 0, 1]);
        //this.solidColorProgram.setUniform('uPointSize', 20);

        if (this.scene) {
            var scene = this.scene;
            var meshes = scene.meshes;
            Object.keys(meshes).forEach(function(meshName) {
                var meshInfo = meshes[meshName];
                meshInfo.primitives.forEach(function(primitive) {
                    var numVerts = scene.accessors[primitive.indices].count;
                    var positionAttrib = scene.accessors[primitive.attributes.POSITION];
                    var minPos = positionAttrib.min;
                    var maxPos = positionAttrib.max;
                    var size = Vec3.sub(Vec3.copy(maxPos), minPos);
                    var center = Vec3.scale(Vec3.add(Vec3.copy(minPos), maxPos), -0.5);
                    var scale = Math.max(size[0], Math.max(size[1], size[2]));
                    ctx.pushModelMatrix();
                    ctx.scale([1/scale, 1/scale, 1/scale]);
                    ctx.translate(center);
                    ctx.bindVertexArray(primitive.vertexArray);
                    ctx.drawElements(ctx.TRIANGLES, numVerts, 0);
                    ctx.popModelMatrix();
                })
            })
        }

        this.gui.draw();
    }
})
<commit_msg>First attempt at displaying node scene tree<commit_after>var Window        = require('pex-sys/Window');
var Draw          = require('pex-draw');
var glslify       = require('./local_modules/glslify-sync');
var PerspCamera   = require('pex-cam/PerspCamera');
var Arcball       = require('pex-cam/Arcball');
var GUI           = require('pex-gui');
var debug         = require('debug').enable('*');
var log           = require('debug')('main');
var loadGLTF      = require('../');
var isBrowser     = require('is-browser');
var Vec3          = require('pex-math/Vec3');
var iterateObject = require('iterate-object');
var Mat4          = require('pex-math/Mat4');

var ASSETS_DIR    = isBrowser ? 'assets' : __dirname + '/assets';

Window.create({
    settings: {
        width: 1280,
        height: 720
    },
    resourcesRaw: {
        showColorsVert    : { text : glslify(__dirname + '/assets/glsl/ShowColors.vert')},
        showColorsFrag    : { text : glslify(__dirname + '/assets/glsl/ShowColors.frag')},
        solidColorVert    : { text : glslify(__dirname + '/assets/glsl/SolidColor.vert')},
        solidColorFrag    : { text : glslify(__dirname + '/assets/glsl/SolidColor.frag')},
        showNormalsVert   : { text : glslify(__dirname + '/assets/glsl/ShowNormals.vert')},
        showNormalsFrag   : { text : glslify(__dirname + '/assets/glsl/ShowNormals.frag')},
        showTexCoordsVert : { text : glslify(__dirname + '/assets/glsl/ShowTexCoords.vert')},
        showTexCoordsFrag : { text : glslify(__dirname + '/assets/glsl/ShowTexCoords.frag')}
    },
    init: function() {
        var ctx = this.getContext();
        this.debugDraw = new Draw(ctx);

        this.gui = new GUI(ctx, this.getWidth(), this.getHeight());
        this.gui.addHeader('Settings');

        this.camera  = new PerspCamera(45, this.getAspectRatio(), 0.01, 200.0);
        this.camera.lookAt([0, 2, 2], [0, 0, 0], [0, 1, 0]);
        ctx.setProjectionMatrix(this.camera.getProjectionMatrix());
        ctx.setViewMatrix(this.camera.getViewMatrix());

        this.arcball = new Arcball(this.camera, this.getWidth(), this.getHeight());
        this.arcball.setRadiusScale(1.5);
        this.arcball.setSpeed(1);
        this.addEventListener(this.arcball);

        this.showColorsProgram = ctx.createProgram(this.resourcesRaw.showColorsVert.text, this.resourcesRaw.showColorsFrag.text);
        this.solidColorProgram = ctx.createProgram(this.resourcesRaw.solidColorVert.text, this.resourcesRaw.solidColorFrag.text);
        this.showNormals = ctx.createProgram(this.resourcesRaw.showNormalsVert.text, this.resourcesRaw.showNormalsFrag.text);
        this.showTexCoords = ctx.createProgram(this.resourcesRaw.showTexCoordsVert.text, this.resourcesRaw.showTexCoordsFrag.text);

        var file = ASSETS_DIR + '/models/duck/duck.gltf';
        //var file = ASSETS_DIR + '/models/rambler/Rambler.gltf';
        //var file = ASSETS_DIR + '/models/SuperMurdoch/SuperMurdoch.gltf';
        loadGLTF(ctx, file, function(err, scene) {
            if (err) {
                log('loadGLTF done', err);
                return;
            }
            log('loadGLTF done');

            this.scene = scene;
        }.bind(this));
    },
    draw: function() {
        var ctx = this.getContext();

        ctx.setClearColor(0.1, 0.1, 0.1, 1.0);
        ctx.clear(ctx.COLOR_BIT | ctx.DEPTH_BIT);
        ctx.setDepthTest(true);

        this.arcball.apply();
        ctx.setViewMatrix(this.camera.getViewMatrix());
        ctx.setLineWidth(2);

        ctx.bindProgram(this.showColorsProgram);
        this.debugDraw.drawPivotAxes(0.5);
        this.debugDraw.setColor([0.5, 0.5, 0.5, 1.0]);
        this.debugDraw.drawGrid([5, 5], 10);

        ctx.bindProgram(this.showNormals);
        this.showNormals.setUniform('uPointSize', 20);
        //ctx.bindProgram(this.showTexCoords);
        //this.showTexCoords.setUniform('uPointSize', 20);
        //ctx.bindProgram(this.showNormals);
        //this.solidColorProgram.setUniform('uColor', [1, 0, 0, 1]);
        //this.solidColorProgram.setUniform('uPointSize', 20);

        function drawMesh(meshInfo) {
            meshInfo.primitives.forEach(function(primitive) {
                var numVerts = scene.accessors[primitive.indices].count;
                var positionAttrib = scene.accessors[primitive.attributes.POSITION];
                var minPos = positionAttrib.min;
                var maxPos = positionAttrib.max;
                var size = Vec3.sub(Vec3.copy(maxPos), minPos);
                var center = Vec3.scale(Vec3.add(Vec3.copy(minPos), maxPos), -0.5);
                var scale = Math.max(size[0], Math.max(size[1], size[2]));
                ctx.pushModelMatrix();
                ctx.scale([1/scale, 1/scale, 1/scale]);
                ctx.translate(center);
                ctx.bindVertexArray(primitive.vertexArray);
                ctx.drawElements(ctx.TRIANGLES, numVerts, 0);
                ctx.popModelMatrix();
            })
        }

        if (this.scene) {
            var scene = this.scene;
            var nodes = scene.nodes;
            var meshes = scene.meshes;
            iterateObject(nodes, function(nodeInfo, nodeName) {
                var localMatrix = Mat4.create();
                //scale44(localMatrix, localMatrix, [2, -2, 2])
                //translate(localMatrix, localMatrix, [-2, 0, 0])
                var matrixStack = [nodeInfo.matrix];
                var parent = nodeInfo.parent;
                while(parent) {
                    if (parent.matrix) {
                        matrixStack.unshift(parent.matrix);
                    }
                    parent = parent.parent;
                }
                //matrixStack.forEach(function(mat) {
                //for(var i=matrixStack.length-1; i>=0; i--) {
                for(var i=0; i<matrixStack.length; i++) {
                    Mat4.mult(localMatrix, matrixStack[i]);
                }
                if (nodeInfo.meshes) {
                    ctx.pushModelMatrix();
                    ctx.setModelMatrix(localMatrix);
                    nodeInfo.meshes.forEach(function(meshId) {
                        var meshInfo = meshes[meshId];
                        drawMesh(meshInfo);
                    });
                    ctx.popModelMatrix();
                }
            });
        }

        this.gui.draw();
    }
})
<|endoftext|>


<commit_before>var should = require('should');
var proxy = require('../lib/main');
var io = require('socket.io-client');

describe('proxy.connect', function() {
    describe('with no arguments', function() {
        describe('and http_proxy env variable defined', function() {
            it('connects to the destination through the proxy', function() {
                process.env.http_proxy = 'http://proxy:8081';
                proxy.init();
                var socket = proxy.connect('https://destination');
                should.exist(socket);
            });
        });
        describe('and http_proxy env variable not defined', function() {
            it('directly connects to the destination', function() {
                process.env.http_proxy = '';
                proxy.init();
                var socket = proxy.connect('http://destination');
                should.exist(socket);
            });
        });
    });
    describe('with proxy server URL', function() {
        it('connects to the specified proxy server', function() {
            proxy.init('http://proxy:8080');
            var socket = proxy.connect('http://destination');
            should.exist(socket);
        });
    });
});
<commit_msg>Changed destination to Google url<commit_after>var should = require('should');
var proxy = require('../lib/main');
var io = require('socket.io-client');

describe('proxy.connect', function() {
    describe('with no arguments', function() {
        describe('and http_proxy env variable defined', function() {
            it('connects to the destination through the proxy', function() {
                process.env.http_proxy = 'http://proxy:8081';
                proxy.init();
                var socket = proxy.connect('https://www.google.com');
                should.exist(socket);
            });
        });
        describe('and http_proxy env variable not defined', function() {
            it('directly connects to the destination', function() {
                process.env.http_proxy = '';
                proxy.init();
                var socket = proxy.connect('http://www.google.com');
                should.exist(socket);
            });
        });
    });
    describe('with proxy server URL', function() {
        it('connects to the specified proxy server', function() {
            proxy.init('http://proxy:8080');
            var socket = proxy.connect('http://www.google.com');
            should.exist(socket);
        });
    });
});
<|endoftext|>