<commit_before>/*global define:true, describe:true , it:true , expect:true,
beforeEach:true, sinon:true, spyOn:true , expect:true */
/* jshint strict: false */
define(function(require) {
    var Go2o = require('go2o');

    describe('Go2o helpers', function() {

        it('should be accessible through the helpers namespace', function() {
            expect(Go2o.helpers).toBeTruthy();
        });
        it('should have a different helper methods', function() {
            var helpers = ['diff', 'extend', 'Parser'];
            expect(Go2o.helpers).toHaveProperties('diff', 'extend', 'Parser');
        });
    });

    describe('Go2o diff helper', function() {
        it('should have a diff helper', function() {
            var diff = Go2o.helpers.diff,
                src = {
                    foo: 'foo',
                    bar: 'bar'
                },
                tgt = {
                    foo: 'foo',
                    baz: 'baz'
                },
                exp = ['bar'];
            expect(diff).toBeTruthy();
            expect(diff(src, tgt)).toMatchObject(exp);
        });

        it('diff helper should handle undefined target argument', function() {
            var diff = Go2o.helpers.diff,
                src = {
                    foo: 'foo',
                    baz: 'baz'
                },
                tgt = null,
                exp = [];
            expect(diff).toBeTruthy();
            expect(diff(src, tgt)).toMatchObject(exp);
        });

        it('diff helper should handle undefined source argument', function() {
            var diff = Go2o.helpers.diff,
                src = null,
                tgt = {
                    foo: 'foo',
                    baz: 'baz'
                },
                exp = ['foo', 'baz'];
            expect(diff).toBeTruthy();
            expect(diff(src, tgt)).toMatchObject(exp);
        });
    });

    describe('extend helper', function() {
        it('should handle no arguments by returning a new object', function() {
            var extend = Go2o.helpers.extend;
            expect(extend()).toMatchObject({});
        });

        it('extend the target object with the properties of objects passed as arguments', function() {
            var source = {},
                target = {
                    foo: 'foo',
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target)).toMatchObject(output);
        });

        it('extend the target object with the properties of multiple objects passed as arguments', function() {
            var source = {},
                target = {
                    foo: 'foo'
                },
                target2 = {
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target, target2)).toMatchObject(output);
        });

        it('target objects should override source properties', function() {
            var source = {
                foo: 'fiz',
                bar: 'biz'
            },
                target = {
                    foo: 'foo',
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target)).toMatchObject(output);
        });

        it('multiple target objects should override source properties', function() {
            var source = {
                foo: 'fiz',
                bar: 'biz'
            },
                target = {
                    foo: 'foo',
                    bar: 'bir'
                },
                target2 = {
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target, target2)).toMatchObject(output);
        });
    });

    describe('Object helper should', function() {
        it('have a flatten method', function() {
            expect(Go2o.helpers.Parser.flatten).toBeTruthy();
            expect(Go2o.helpers.Parser.flatten).toBeOfType('function');
        });

        it('have a flatten unflatten', function() {
            expect(Go2o.helpers.Parser.unflatten).toBeTruthy();
            expect(Go2o.helpers.Parser.unflatten).toBeOfType('function');
        });

        it('have a flatten glob', function() {
            expect(Go2o.helpers.Parser.glob).toBeTruthy();
            expect(Go2o.helpers.Parser.glob).toBeOfType('function');
        });

        it('flatten medthod should take an object and return a map with string paths to values', function() {
            var source = [{
                "impact": {
                    "id": "1",
                    "name": "Taxes",
                    "direction": "UP"
                },
                "explanation": "Lorem ipsum"
            }, {
                "impact": {
                    "id": "2",
                    "name": "Jobs",
                    "direction": "UP"
                },
                "explanation": "Lorem ipsum"
            }];

            var expected = {
                "0.impact.id": "1",
                "0.impact.name": "Taxes",
                "0.impact.direction": "UP",
                "0.explanation": "Lorem ipsum",
                "1.impact.id": "2",
                "1.impact.name": "Jobs",
                "1.impact.direction": "UP",
                "1.explanation": "Lorem ipsum"
            };
            var Parser = Go2o.helpers.Parser;

            expect(Parser.flatten(source)).toMatchObject(expected);
        });

        it('unflatten medthod should take a map with string paths and return an object', function() {
            var expected = [{
                "impact": {
                    "id": "1",
                    "name": "Taxes",
                    "direction": "UP"
                },
                "explanation": "Lorem ipsum"
            }, {
                "impact": {
                    "id": "2",
                    "name": "Jobs",
                    "direction": "UP"
                },
                "explanation": "Lorem ipsum"
            }];

            var source = {
                "0.impact.id": "1",
                "0.impact.name": "Taxes",
                "0.impact.direction": "UP",
                "0.explanation": "Lorem ipsum",
                "1.impact.id": "2",
                "1.impact.name": "Jobs",
                "1.impact.direction": "UP",
                "1.explanation": "Lorem ipsum"
            };
            var Parser = Go2o.helpers.Parser;

            expect(Parser.unflatten(source)).toMatchObject(expected);
        });

        it('glob should filter a map properties using a regexp', function() {
            var source = {
                "0.impact.id": "1",
                "0.impact.name": "Taxes",
                "0.impact.direction": "UP",
                "0.explanation": "Lorem ipsum",
                "1.impact.id": "2",
                "1.impact.name": "Jobs",
                "1.impact.direction": "UP",
                "1.explanation": "Lorem ipsum"
            };
            var pattern = /\d+\.explanation/;
            var expected = {
                '0.explanation': 'Lorem ipsum',
                '1.explanation': 'Lorem ipsum'
            };
            var glob = Go2o.helpers.Parser.glob;

            expect(glob(source, pattern)).toMatchObject(expected);
        });
    });

    describe('Go2o', function() {
        it('should have an initialization method', function() {
            var go = new Go2o();
            expect(go.initialized).toBeTruthy();
        });

        it('should apply transforms', function(){
            var schema = {
                pre: ['flattenPaths'],
                post: ['mergeOrphans', 'unflattenPaths'],
                transforms: {
                    'amendments.#.impacts.#.impact': {
                        rename: {
                            glob: true,
                            matcher: /amendments\.(\d+)\.impacts\.(\d+)\.impact/,
                            execute: function(key, path, options) {
                                return key.replace('.impact.', '.');
                            }
                        }
                    }
                }
            };
            var source = {
                amendments:[
                    {
                        id:1,
                        impacts:[
                            {
                                id:1,
                                impact:{
                                    id:11,
                                    type:'impact'
                                }
                            },
                            {
                                id:2,
                                impact:{
                                    id:22,
                                    type:'impact'
                                }
                            }
                        ]
                    },
                    {
                        id:2,
                        impacts:[
                            {
                                id:3,
                                impact:{
                                    id:33,
                                    type:'impact'
                                }
                            },
                            {
                                id:4,
                                impact:{
                                    id:44,
                                    type:'impact'
                                }
                            }
                        ]
                    }
                ]
            };

            var target = {
                amendments:[
                    {
                        id:1,
                        impacts:[
                            {

                                id:1,
                                //id:11,
                                type:'impact'
                            },
                            {
                                id:2,
                                //id:22,
                                type:'impact'
                            }
                        ]
                    },
                    {
                        id:2,
                        impacts:[
                            {
                                id:3,
                                //id:33,
                                type:'impact'

                            },
                            {
                                id:4,
                                //id:44,
                                type:'impact'

                            }
                        ]
                    }
                ]
            };
            var go = new Go2o(schema);
            var output = go.run(source);
            console.log(output)
            expect(output).toMatchObject(target);
        });
    });
});<commit_msg>SPEC: Update specs.<commit_after>/*global define:true, describe:true , it:true , expect:true,
beforeEach:true, sinon:true, spyOn:true , expect:true */
/* jshint strict: false */
define(function(require) {
    var Go2o = require('go2o');

    describe('Go2o helpers', function() {

        it('should be accessible through the helpers namespace', function() {
            expect(Go2o.helpers).toBeTruthy();
        });
        it('should have a different helper methods', function() {
            var helpers = ['diff', 'extend', 'Parser'];
            expect(Go2o.helpers).toHaveProperties('diff', 'extend', 'Parser');
        });
    });

    describe('Go2o diff helper', function() {
        it('should have a diff helper', function() {
            var diff = Go2o.helpers.diff,
                src = {
                    foo: 'foo',
                    bar: 'bar'
                },
                tgt = {
                    foo: 'foo',
                    baz: 'baz'
                },
                exp = ['bar'];
            expect(diff).toBeTruthy();
            expect(diff(src, tgt)).toMatchObject(exp);
        });

        it('diff helper should handle undefined target argument', function() {
            var diff = Go2o.helpers.diff,
                src = {
                    foo: 'foo',
                    baz: 'baz'
                },
                tgt = null,
                exp = [];
            expect(diff).toBeTruthy();
            expect(diff(src, tgt)).toMatchObject(exp);
        });

        it('diff helper should handle undefined source argument', function() {
            var diff = Go2o.helpers.diff,
                src = null,
                tgt = {
                    foo: 'foo',
                    baz: 'baz'
                },
                exp = ['foo', 'baz'];
            expect(diff).toBeTruthy();
            expect(diff(src, tgt)).toMatchObject(exp);
        });
    });

    describe('extend helper', function() {
        it('should handle no arguments by returning a new object', function() {
            var extend = Go2o.helpers.extend;
            expect(extend()).toMatchObject({});
        });

        it('extend the target object with the properties of objects passed as arguments', function() {
            var source = {},
                target = {
                    foo: 'foo',
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target)).toMatchObject(output);
        });

        it('extend the target object with the properties of multiple objects passed as arguments', function() {
            var source = {},
                target = {
                    foo: 'foo'
                },
                target2 = {
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target, target2)).toMatchObject(output);
        });

        it('target objects should override source properties', function() {
            var source = {
                foo: 'fiz',
                bar: 'biz'
            },
                target = {
                    foo: 'foo',
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target)).toMatchObject(output);
        });

        it('multiple target objects should override source properties', function() {
            var source = {
                foo: 'fiz',
                bar: 'biz'
            },
                target = {
                    foo: 'foo',
                    bar: 'bir'
                },
                target2 = {
                    bar: 'bar'
                },
                output = {
                    foo: 'foo',
                    bar: 'bar'
                },
                extend = Go2o.helpers.extend;
            expect(extend(source, target, target2)).toMatchObject(output);
        });
    });

    describe('Object helper should', function() {
        it('have a flatten method', function() {
            expect(Go2o.helpers.Parser.flatten).toBeTruthy();
            expect(Go2o.helpers.Parser.flatten).toBeOfType('function');
        });

        it('have a flatten unflatten', function() {
            expect(Go2o.helpers.Parser.unflatten).toBeTruthy();
            expect(Go2o.helpers.Parser.unflatten).toBeOfType('function');
        });

        it('have a flatten glob', function() {
            expect(Go2o.helpers.Parser.glob).toBeTruthy();
            expect(Go2o.helpers.Parser.glob).toBeOfType('function');
        });

        it('flatten medthod should take an object and return a map with string paths to values', function() {
            var source = [{
                "impact": {
                    "id": "1",
                    "name": "Taxes",
                    "direction": "UP"
                },
                "explanation": "Lorem ipsum"
            }, {
                "impact": {
                    "id": "2",
                    "name": "Jobs",
                    "direction": "UP"
                },
                "explanation": "Lorem ipsum"
            }];

            var expected = {
                "0.impact.id": "1",
                "0.impact.name": "Taxes",
                "0.impact.direction": "UP",
                "0.explanation": "Lorem ipsum",
                "1.impact.id": "2",
                "1.impact.name": "Jobs",
                "1.impact.direction": "UP",
                "1.explanation": "Lorem ipsum"
            };
            var Parser = Go2o.helpers.Parser;

            expect(Parser.flatten(source)).toMatchObject(expected);
        });

        it('unflatten medthod should take a map with string paths and return an object', function() {
            var expected = [{
                "impact": {
                    "id": "1",
                    "name": "Taxes",
                    "direction": "UP"
                },
                "explanation": "Lorem ipsum"
            }, {
                "impact": {
                    "id": "2",
                    "name": "Jobs",
                    "direction": "UP"
                },
                "explanation": "Lorem ipsum"
            }];

            var source = {
                "0.impact.id": "1",
                "0.impact.name": "Taxes",
                "0.impact.direction": "UP",
                "0.explanation": "Lorem ipsum",
                "1.impact.id": "2",
                "1.impact.name": "Jobs",
                "1.impact.direction": "UP",
                "1.explanation": "Lorem ipsum"
            };
            var Parser = Go2o.helpers.Parser;

            expect(Parser.unflatten(source)).toMatchObject(expected);
        });

        it('glob should filter a map properties using a regexp', function() {
            var source = {
                "0.impact.id": "1",
                "0.impact.name": "Taxes",
                "0.impact.direction": "UP",
                "0.explanation": "Lorem ipsum",
                "1.impact.id": "2",
                "1.impact.name": "Jobs",
                "1.impact.direction": "UP",
                "1.explanation": "Lorem ipsum"
            };
            var pattern = /\d+\.explanation/;
            var expected = {
                '0.explanation': 'Lorem ipsum',
                '1.explanation': 'Lorem ipsum'
            };
            var glob = Go2o.helpers.Parser.glob;

            expect(glob(source, pattern)).toMatchObject(expected);
        });
    });

    describe('Go2o', function() {
        it('should have an initialization method', function() {
            var go = new Go2o();
            expect(go.initialized).toBeTruthy();
        });

        it('should apply transforms', function() {
            var schema = {
                pre: ['flattenPaths'],
                post: ['mergeOrphans', 'unflattenPaths'],
                transforms: {
                    'amendments.#.impacts.#.impact': {
                        rename: {
                            glob: true,
                            matcher: /amendments\.(\d+)\.impacts\.(\d+)\.impact/,
                            execute: function(key, path, options) {
                                return key.replace('.impact.', '.');
                            }
                        }
                    }
                }
            };
            var source = {
                amendments: [{
                    id: 1,
                    impacts: [{
                        id: 1,
                        impact: {
                            id: 11,
                            type: 'impact'
                        }
                    }, {
                        id: 2,
                        impact: {
                            id: 22,
                            type: 'impact'
                        }
                    }]
                }, {
                    id: 2,
                    impacts: [{
                        id: 3,
                        impact: {
                            id: 33,
                            type: 'impact'
                        }
                    }, {
                        id: 4,
                        impact: {
                            id: 44,
                            type: 'impact'
                        }
                    }]
                }]
            };

            var target = {
                amendments: [{
                    id: 1,
                    impacts: [{

                        id: 1,
                        //id:11,
                        type: 'impact'
                    }, {
                        id: 2,
                        //id:22,
                        type: 'impact'
                    }]
                }, {
                    id: 2,
                    impacts: [{
                        id: 3,
                        //id:33,
                        type: 'impact'

                    }, {
                        id: 4,
                        //id:44,
                        type: 'impact'

                    }]
                }]
            };
            var go = new Go2o(schema);
            var output = go.run(source);
            expect(output).toMatchObject(target);
        });

        it('should handle source Array transformations', function() {
            var schema = {
                pre: ['flattenPaths'],
                post: ['mergeOrphans', 'unflattenPaths'],
                transforms: {
                    '#.impacts.#.impact': {
                        rename: {
                            glob: true,
                            matcher: /(\d+)\.impacts\.(\d+)\.impact/,
                            execute: function(key, path, options) {
                                return key.replace('.impact.', '.');
                            }
                        }
                    }
                }
            };
            var source =
                [{
                id: 1,
                impacts: [{
                    id: 1,
                    impact: {
                        id: 11,
                        type: 'impact'
                    }
                }, {
                    id: 2,
                    impact: {
                        id: 22,
                        type: 'impact'
                    }
                }]
            }, {
                id: 2,
                impacts: [{
                    id: 3,
                    impact: {
                        id: 33,
                        type: 'impact'
                    }
                }, {
                    id: 4,
                    impact: {
                        id: 44,
                        type: 'impact'
                    }
                }]
            }];

            var target = [{
                id: 1,
                impacts: [{

                    id: 1,
                    //id:11,
                    type: 'impact'
                }, {
                    id: 2,
                    //id:22,
                    type: 'impact'
                }]
            }, {
                id: 2,
                impacts: [{
                    id: 3,
                    //id:33,
                    type: 'impact'

                }, {
                    id: 4,
                    //id:44,
                    type: 'impact'

                }]
            }];
            var go = new Go2o(schema);
            var output = go.run(source);
            expect(output).toMatchObject(target);
        });
    });
});<|endoftext|>


<commit_before>import { assert }    from 'chai';
import TyphonEvents  from '../../src/TyphonEvents';

/* eslint-disable no-undef */

describe('Events', () =>
{
   let callbacks, eventbus;

   beforeEach(() => { callbacks = {}; eventbus = new TyphonEvents(); });

   it('set / get name', () =>
   {
      eventbus.setEventbusName('testname');
      assert(eventbus.getEventbusName() === 'testname');

      eventbus = new TyphonEvents('testname2');
      assert(eventbus.getEventbusName() === 'testname2');
   });

   it('forEachEvent', () =>
   {
      const callback1 = () => {};
      const callback2 = () => {};
      const callback3 = () => {};
      const callback3A = () => {};

      const context1 = {};
      const context2 = {};
      const context3 = {};
      const context3A = {};

      const allCallbacks = [callback1, callback2, callback3, callback3A];
      const allContexts = [context1, context2, context3, context3A];
      const allNames = ['test:trigger', 'test:trigger2', 'test:trigger3', 'test:trigger3'];

      eventbus.on('test:trigger', callback1, context1);
      eventbus.on('test:trigger2', callback2, context2);
      eventbus.on('test:trigger3', callback3, context3);
      eventbus.on('test:trigger3', callback3A, context3A);

      let cntr = 0;

      eventbus.forEachEvent((name, callback, context) =>
      {
         assert.strictEqual(name, allNames[cntr]);
         assert.strictEqual(callback, allCallbacks[cntr]);
         assert.strictEqual(context, allContexts[cntr]);
         cntr++;
      });
   });

   it('getEventNames', () =>
   {
      eventbus.on('test:trigger', () => {});
      eventbus.on('test:trigger2', () => {});
      eventbus.on('test:trigger3', () => {});
      eventbus.on('test:trigger3', () => {});

      const eventNames = eventbus.getEventNames();

      assert.strictEqual(JSON.stringify(eventNames), '["test:trigger","test:trigger2","test:trigger3"]');
   });

   it('trigger', () =>
   {
      eventbus.on('test:trigger', () => { callbacks.testTrigger = true; });
      eventbus.trigger('test:trigger');
      assert(callbacks.testTrigger);
   });

   it('trigger (once)', () =>
   {
      callbacks.testTriggerOnce = 0;
      eventbus.once('test:trigger:once', () => { callbacks.testTriggerOnce++; });
      eventbus.trigger('test:trigger:once');
      eventbus.trigger('test:trigger:once');
      assert(callbacks.testTriggerOnce === 1);
   });

   it('trigger (listenTo)', () =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerCount = 0;

      test.listenTo(eventbus, 'test:trigger', () => { callbacks.testTriggerCount++; });

      eventbus.trigger('test:trigger');

      assert(callbacks.testTriggerCount === 1);

      // Test stop listening such that `test:trigger` is no longer registered.
      test.stopListening(eventbus, 'test:trigger');

      eventbus.trigger('test:trigger');

      assert(callbacks.testTriggerCount === 1);
   });

   it('trigger (listenToOnce)', () =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerOnce = 0;

      test.listenToOnce(eventbus, 'test:trigger', () => { callbacks.testTriggerOnce++; });

      eventbus.trigger('test:trigger');

      assert(callbacks.testTriggerOnce === 1);

      eventbus.trigger('test:trigger');

      assert(callbacks.testTriggerOnce === 1);
   });

   it('triggerDefer', (done) =>
   {
      eventbus.on('test:trigger:defer', () => { done(); });
      eventbus.triggerDefer('test:trigger:defer');
   });

   it('triggerDefer (once)', (done) =>
   {
      callbacks.testTriggerOnce = 0;
      eventbus.once('test:trigger:once', () => { callbacks.testTriggerOnce++; });
      eventbus.on('test:trigger:verify', () => { assert(callbacks.testTriggerOnce === 1); done(); });

      eventbus.triggerDefer('test:trigger:once');
      eventbus.triggerDefer('test:trigger:once');
      eventbus.triggerDefer('test:trigger:verify');
   });
   it('triggerDefer (listenTo)', (done) =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerCount = 0;

      test.listenTo(eventbus, 'test:trigger', () => { callbacks.testTriggerCount++; });

      eventbus.on('test:trigger:verify', () =>
      {
         assert(callbacks.testTriggerCount === 1);

         // Test stop listening such that `test:trigger` is no longer registered.
         test.stopListening(eventbus, 'test:trigger');
      });

      eventbus.on('test:trigger:verify:done', () => { assert(callbacks.testTriggerCount === 1); done(); });

      eventbus.triggerDefer('test:trigger');

      eventbus.triggerDefer('test:trigger:verify');

      eventbus.triggerDefer('test:trigger');

      eventbus.triggerDefer('test:trigger:verify:done');
   });

   it('triggerDefer (listenToOnce)', (done) =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerOnce = 0;

      test.listenToOnce(eventbus, 'test:trigger', () => { callbacks.testTriggerOnce++; });
      eventbus.on('test:trigger:verify', () => { assert(callbacks.testTriggerOnce === 1); done(); });

      eventbus.triggerDefer('test:trigger');
      eventbus.triggerDefer('test:trigger');
      eventbus.triggerDefer('test:trigger:verify');
   });

   it('triggerSync-0', () =>
   {
      const result = eventbus.triggerSync('test:trigger:sync0');

      assert(!Array.isArray(result));
      assert(result === void 0);
   });

   it('triggerSync-1', () =>
   {
      eventbus.on('test:trigger:sync1', () => { callbacks.testTriggerSync1 = true; return 'foo'; });

      const result = eventbus.triggerSync('test:trigger:sync1');

      assert(callbacks.testTriggerSync1);
      assert(!Array.isArray(result));
      assert(result === 'foo');
   });

   it('triggerSync-2', () =>
   {
      eventbus.on('test:trigger:sync2', () => { callbacks.testTriggerSync2A = true; return 'foo'; });
      eventbus.on('test:trigger:sync2', () => { callbacks.testTriggerSync2B = true; return 'bar'; });

      const results = eventbus.triggerSync('test:trigger:sync2');

      assert(callbacks.testTriggerSync2A);
      assert(callbacks.testTriggerSync2B);
      assert(Array.isArray(results));
      assert(results.length === 2);
      assert(results[0] === 'foo' && results[1] === 'bar');
   });

   it('triggerSync (on / off)', () =>
   {
      eventbus.on('test:trigger:sync:off', () => { callbacks.testTriggerSyncOff = true; return true; });
      eventbus.off('test:trigger:sync:off');
      assert(eventbus.triggerSync('test:trigger:sync:off') === undefined);
      assert(callbacks.testTriggerSyncOff === undefined);
   });

   it('triggerSync-1 (once)', () =>
   {
      callbacks.testTriggerOnce = 0;

      eventbus.once('test:trigger:once', () => { callbacks.testTriggerOnce++; return 'foo'; });

      let result = eventbus.triggerSync('test:trigger:once');

      assert(callbacks.testTriggerOnce === 1);
      assert(!Array.isArray(result));
      assert(result === 'foo');

      result = eventbus.triggerSync('test:trigger:once');

      assert(callbacks.testTriggerOnce === 1);
      assert(result === void 0);
   });

   it('triggerSync-1 (listenTo)', () =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerCount = 0;

      test.listenTo(eventbus, 'test:trigger:sync', () => { callbacks.testTriggerCount++; return 'foo'; });

      let result = eventbus.triggerSync('test:trigger:sync');

      assert(callbacks.testTriggerCount === 1);
      assert(!Array.isArray(result));
      assert(result === 'foo');

      test.stopListening(eventbus, 'test:trigger:sync');

      result = eventbus.triggerSync('test:trigger:sync');

      assert(callbacks.testTriggerCount === 1);
      assert(result === void 0);
   });

   it('triggerSync-1 (listenToOnce)', () =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerOnce = 0;

      test.listenToOnce(eventbus, 'test:trigger:once', () => { callbacks.testTriggerOnce++; return 'foo'; });

      let result = eventbus.triggerSync('test:trigger:once');

      assert(callbacks.testTriggerOnce === 1);
      assert(!Array.isArray(result));
      assert(result === 'foo');

      result = eventbus.triggerSync('test:trigger:once');

      assert(callbacks.testTriggerOnce === 1);
      assert(result === void 0);
   });

   it('triggerSync (Promise)', (done) =>
   {
      eventbus.on('test:trigger:sync:then', () =>
      {
         callbacks.testTriggerSyncThen = true;
         return Promise.resolve('foobar');
      });

      const promise = eventbus.triggerSync('test:trigger:sync:then');

      assert(promise instanceof Promise);

      promise.then((result) =>
      {
         assert(callbacks.testTriggerSyncThen);
         assert(result === 'foobar');
         done();
      });
   });

   it('triggerAsync', (done) =>
   {
      eventbus.on('test:trigger:async', () => { callbacks.testTriggerAsync = true; return 'foo'; });
      eventbus.on('test:trigger:async', () => { callbacks.testTriggerAsync2 = true; return 'bar'; });

      const promise = eventbus.triggerAsync('test:trigger:async');

      assert(promise instanceof Promise);

      // triggerAsync resolves all Promises by Promise.all() so result is an array.
      promise.then((result) =>
      {
         assert(callbacks.testTriggerAsync);
         assert(callbacks.testTriggerAsync2);
         assert(result[0] === 'foo');
         assert(result[1] === 'bar');
         done();
      });
   });

   it('triggerAsync (once)', (done) =>
   {
      callbacks.testTriggerOnce = 0;

      eventbus.once('test:trigger:once', () => { callbacks.testTriggerOnce++; return 'foo'; });

      const promise = eventbus.triggerAsync('test:trigger:once');

      assert(callbacks.testTriggerOnce === 1);
      assert(promise instanceof Promise);

      const promise2 = eventbus.triggerAsync('test:trigger:once');

      assert(callbacks.testTriggerOnce === 1);
      assert(promise2 instanceof Promise);

      // triggerAsync resolves all Promises by Promise.all() or Promise.resolve() so result is a string.
      promise.then((result) =>
      {
         assert(callbacks.testTriggerOnce === 1);
         assert(result === 'foo');
         done();
      });
   });

   it('triggerAsync (listenTo)', (done) =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerCount = 0;

      test.listenTo(eventbus, 'test:trigger:async', () => { callbacks.testTriggerCount++; return 'foo'; });

      let promise = eventbus.triggerAsync('test:trigger:async');

      assert(promise instanceof Promise);

      promise.then((result) =>
      {
         assert(callbacks.testTriggerCount === 1);
         assert(result === 'foo');
      });

      test.stopListening(eventbus, 'test:trigger:async');

      promise = eventbus.triggerAsync('test:trigger:async');

      promise.then((result) =>
      {
         assert(result === void 0);
         assert(callbacks.testTriggerCount === 1);
         done();
      });
   });

   it('triggerAsync (listenToOnce)', (done) =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerOnce = 0;

      test.listenToOnce(eventbus, 'test:trigger:once', () => { callbacks.testTriggerOnce++; return 'foo'; });

      const promise = eventbus.triggerAsync('test:trigger:once');

      assert(callbacks.testTriggerOnce === 1);
      assert(promise instanceof Promise);

      const promise2 = eventbus.triggerAsync('test:trigger:once');

      assert(callbacks.testTriggerOnce === 1);
      assert(promise2 instanceof Promise);

      // triggerAsync resolves all Promises by Promise.all() or Promise.resolve() so result is a string.
      promise.then((result) =>
      {
         assert(callbacks.testTriggerOnce === 1);
         assert(result === 'foo');
         done();
      });
   });
});<commit_msg>added specific assert tests<commit_after>import { assert }    from 'chai';
import TyphonEvents  from '../../src/TyphonEvents';

/* eslint-disable no-undef */

describe('Events', () =>
{
   let callbacks, eventbus;

   beforeEach(() => { callbacks = {}; eventbus = new TyphonEvents(); });

   it('set / get name', () =>
   {
      eventbus.setEventbusName('testname');
      assert.strictEqual(eventbus.getEventbusName(), 'testname');

      eventbus = new TyphonEvents('testname2');
      assert.strictEqual(eventbus.getEventbusName(), 'testname2');
   });

   it('forEachEvent', () =>
   {
      const callback1 = () => {};
      const callback2 = () => {};
      const callback3 = () => {};
      const callback3A = () => {};

      const context1 = {};
      const context2 = {};
      const context3 = {};
      const context3A = {};

      const allCallbacks = [callback1, callback2, callback3, callback3A];
      const allContexts = [context1, context2, context3, context3A];
      const allNames = ['test:trigger', 'test:trigger2', 'test:trigger3', 'test:trigger3'];

      eventbus.on('test:trigger', callback1, context1);
      eventbus.on('test:trigger2', callback2, context2);
      eventbus.on('test:trigger3', callback3, context3);
      eventbus.on('test:trigger3', callback3A, context3A);

      let cntr = 0;

      eventbus.forEachEvent((name, callback, context) =>
      {
         assert.strictEqual(name, allNames[cntr]);
         assert.strictEqual(callback, allCallbacks[cntr]);
         assert.strictEqual(context, allContexts[cntr]);
         cntr++;
      });
   });

   it('getEventNames', () =>
   {
      eventbus.on('test:trigger', () => {});
      eventbus.on('test:trigger2', () => {});
      eventbus.on('test:trigger3', () => {});
      eventbus.on('test:trigger3', () => {});

      const eventNames = eventbus.getEventNames();

      assert.strictEqual(JSON.stringify(eventNames), '["test:trigger","test:trigger2","test:trigger3"]');
   });

   it('trigger', () =>
   {
      eventbus.on('test:trigger', () => { callbacks.testTrigger = true; });
      eventbus.trigger('test:trigger');

      assert.strictEqual(eventbus.eventCount, 1);

      assert.isTrue(callbacks.testTrigger);
   });

   it('trigger (once)', () =>
   {
      callbacks.testTriggerOnce = 0;
      eventbus.once('test:trigger:once', () => { callbacks.testTriggerOnce++; });

      assert.strictEqual(eventbus.eventCount, 1);

      eventbus.trigger('test:trigger:once');

      assert.strictEqual(eventbus.eventCount, 0);

      eventbus.trigger('test:trigger:once');

      assert.strictEqual(eventbus.eventCount, 0);

      assert.strictEqual(callbacks.testTriggerOnce, 1);
   });

   it('trigger (listenTo)', () =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerCount = 0;

      test.listenTo(eventbus, 'test:trigger', () => { callbacks.testTriggerCount++; });

      eventbus.trigger('test:trigger');

      assert.strictEqual(eventbus.eventCount, 1);

      assert.strictEqual(callbacks.testTriggerCount, 1);

      // Test stop listening such that `test:trigger` is no longer registered.
      test.stopListening(eventbus, 'test:trigger');

      eventbus.trigger('test:trigger');

      assert.strictEqual(eventbus.eventCount, 0);

      assert.strictEqual(callbacks.testTriggerCount, 1);
   });

   it('trigger (listenToOnce)', () =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerOnce = 0;

      test.listenToOnce(eventbus, 'test:trigger', () => { callbacks.testTriggerOnce++; });

      assert.strictEqual(eventbus.eventCount, 1);

      eventbus.trigger('test:trigger');

      assert.strictEqual(eventbus.eventCount, 0);

      assert.strictEqual(callbacks.testTriggerOnce, 1);

      eventbus.trigger('test:trigger');

      assert.strictEqual(eventbus.eventCount, 0);

      assert.strictEqual(callbacks.testTriggerOnce, 1);
   });

   it('triggerDefer', (done) =>
   {
      eventbus.on('test:trigger:defer', () =>
      {
         assert.strictEqual(eventbus.eventCount, 1);

         done();
      });

      assert.strictEqual(eventbus.eventCount, 1);

      eventbus.triggerDefer('test:trigger:defer');
   });

   it('triggerDefer (once)', (done) =>
   {
      callbacks.testTriggerOnce = 0;

      eventbus.once('test:trigger:once', () => { callbacks.testTriggerOnce++; });

      assert.strictEqual(eventbus.eventCount, 1);

      eventbus.on('test:trigger:verify', () =>
      {
         assert.strictEqual(callbacks.testTriggerOnce, 1);

         assert.strictEqual(eventbus.eventCount, 1);

         done();
      });

      assert.strictEqual(eventbus.eventCount, 2);

      eventbus.triggerDefer('test:trigger:once');

      assert.strictEqual(eventbus.eventCount, 2); // Trigger is deferred so 2 events still exist.

      eventbus.triggerDefer('test:trigger:once');

      assert.strictEqual(eventbus.eventCount, 2); // Trigger is deferred so 2 events still exist.

      eventbus.triggerDefer('test:trigger:verify');
   });

   it('triggerDefer (listenTo)', (done) =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerCount = 0;

      test.listenTo(eventbus, 'test:trigger', () => { callbacks.testTriggerCount++; });

      assert.strictEqual(eventbus.eventCount, 1);

      eventbus.on('test:trigger:verify', () =>
      {
         assert.strictEqual(callbacks.testTriggerCount, 1);

         // Test stop listening such that `test:trigger` is no longer registered.
         test.stopListening(eventbus, 'test:trigger');

         assert.strictEqual(eventbus.eventCount, 2);
      });

      assert.strictEqual(eventbus.eventCount, 2);

      eventbus.on('test:trigger:verify:done', () =>
      {
         assert.strictEqual(callbacks.testTriggerCount, 1);

         assert.strictEqual(eventbus.eventCount, 2);

         done();
      });

      assert.strictEqual(eventbus.eventCount, 3);

      eventbus.triggerDefer('test:trigger');

      eventbus.triggerDefer('test:trigger:verify');

      eventbus.triggerDefer('test:trigger');

      eventbus.triggerDefer('test:trigger:verify:done');

      assert.strictEqual(eventbus.eventCount, 3);
   });

   it('triggerDefer (listenToOnce)', (done) =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerOnce = 0;

      test.listenToOnce(eventbus, 'test:trigger', () =>
      {
         callbacks.testTriggerOnce++;

         assert.strictEqual(eventbus.eventCount, 1);
      });

      assert.strictEqual(eventbus.eventCount, 1);

      eventbus.on('test:trigger:verify', () =>
      {
         assert.strictEqual(callbacks.testTriggerOnce, 1);

         assert.strictEqual(eventbus.eventCount, 1);

         done();
      });

      assert.strictEqual(eventbus.eventCount, 2);

      eventbus.triggerDefer('test:trigger');
      eventbus.triggerDefer('test:trigger');
      eventbus.triggerDefer('test:trigger:verify');

      assert.strictEqual(eventbus.eventCount, 2);
   });

   it('triggerSync-0', () =>
   {
      const result = eventbus.triggerSync('test:trigger:sync0');

      assert.strictEqual(eventbus.eventCount, 0);

      assert.isNotArray(result);
      assert.isUndefined(result);
   });

   it('triggerSync-1', () =>
   {
      eventbus.on('test:trigger:sync1', () => { callbacks.testTriggerSync1 = true; return 'foo'; });

      assert.strictEqual(eventbus.eventCount, 1);

      const result = eventbus.triggerSync('test:trigger:sync1');

      assert.isTrue(callbacks.testTriggerSync1);
      assert.isNotArray(result);
      assert.strictEqual(result, 'foo');
   });

   it('triggerSync-2', () =>
   {
      eventbus.on('test:trigger:sync2', () => { callbacks.testTriggerSync2A = true; return 'foo'; });
      eventbus.on('test:trigger:sync2', () => { callbacks.testTriggerSync2B = true; return 'bar'; });

      assert.strictEqual(eventbus.eventCount, 2);

      const results = eventbus.triggerSync('test:trigger:sync2');

      assert.isTrue(callbacks.testTriggerSync2A);
      assert.isTrue(callbacks.testTriggerSync2B);
      assert.isArray(results);
      assert.strictEqual(results.length, 2);
      assert.strictEqual(results[0], 'foo');
      assert.strictEqual(results[1], 'bar');
   });

   it('triggerSync (on / off)', () =>
   {
      assert.strictEqual(eventbus.eventCount, 0);

      eventbus.on('test:trigger:sync:off', () => { callbacks.testTriggerSyncOff = true; return true; });

      assert.strictEqual(eventbus.eventCount, 1);

      eventbus.off('test:trigger:sync:off');

      assert.strictEqual(eventbus.eventCount, 0);

      assert.isUndefined(eventbus.triggerSync('test:trigger:sync:off'));
      assert.isUndefined(callbacks.testTriggerSyncOff);
   });

   it('triggerSync-1 (once)', () =>
   {
      callbacks.testTriggerOnce = 0;

      eventbus.once('test:trigger:once', () => { callbacks.testTriggerOnce++; return 'foo'; });

      assert.strictEqual(eventbus.eventCount, 1);

      let result = eventbus.triggerSync('test:trigger:once');

      assert.strictEqual(eventbus.eventCount, 0);

      assert.strictEqual(callbacks.testTriggerOnce, 1);
      assert.isNotArray(result);
      assert.strictEqual(result, 'foo');

      result = eventbus.triggerSync('test:trigger:once');

      assert.strictEqual(callbacks.testTriggerOnce, 1);
      assert.isUndefined(result);
   });

   it('triggerSync-1 (listenTo)', () =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerCount = 0;

      test.listenTo(eventbus, 'test:trigger:sync', () => { callbacks.testTriggerCount++; return 'foo'; });

      assert.strictEqual(eventbus.eventCount, 1);

      let result = eventbus.triggerSync('test:trigger:sync');

      assert.strictEqual(callbacks.testTriggerCount, 1);
      assert.isNotArray(result);
      assert.strictEqual(result, 'foo');

      assert.strictEqual(eventbus.eventCount, 1);

      test.stopListening(eventbus, 'test:trigger:sync');

      assert.strictEqual(eventbus.eventCount, 0);

      result = eventbus.triggerSync('test:trigger:sync');

      assert.strictEqual(callbacks.testTriggerCount, 1);
      assert.isUndefined(result);
   });

   it('triggerSync-1 (listenToOnce)', () =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerOnce = 0;

      test.listenToOnce(eventbus, 'test:trigger:once', () => { callbacks.testTriggerOnce++; return 'foo'; });

      assert.strictEqual(eventbus.eventCount, 1);

      let result = eventbus.triggerSync('test:trigger:once');

      assert.strictEqual(eventbus.eventCount, 0);

      assert.strictEqual(callbacks.testTriggerOnce, 1);
      assert.isNotArray(result);
      assert.strictEqual(result, 'foo');

      result = eventbus.triggerSync('test:trigger:once');

      assert.strictEqual(callbacks.testTriggerOnce, 1);
      assert.isUndefined(result);
   });

   it('triggerSync (Promise)', (done) =>
   {
      eventbus.on('test:trigger:sync:then', () =>
      {
         callbacks.testTriggerSyncThen = true;

         return Promise.resolve('foobar');
      });

      assert.strictEqual(eventbus.eventCount, 1);

      const promise = eventbus.triggerSync('test:trigger:sync:then');

      assert(promise instanceof Promise);

      promise.then((result) =>
      {
         assert.isTrue(callbacks.testTriggerSyncThen);
         assert.strictEqual(result, 'foobar');
         done();
      });
   });

   it('triggerAsync', (done) =>
   {
      eventbus.on('test:trigger:async', () => { callbacks.testTriggerAsync = true; return 'foo'; });
      eventbus.on('test:trigger:async', () => { callbacks.testTriggerAsync2 = true; return 'bar'; });

      assert.strictEqual(eventbus.eventCount, 2);

      const promise = eventbus.triggerAsync('test:trigger:async');

      assert(promise instanceof Promise);

      // triggerAsync resolves all Promises by Promise.all() so result is an array.
      promise.then((result) =>
      {
         assert.isTrue(callbacks.testTriggerAsync);
         assert.isTrue(callbacks.testTriggerAsync2);
         assert.strictEqual(result[0], 'foo');
         assert.strictEqual(result[1], 'bar');
         done();
      });
   });

   it('triggerAsync (once)', (done) =>
   {
      callbacks.testTriggerOnce = 0;

      assert.strictEqual(eventbus.eventCount, 0);

      eventbus.once('test:trigger:once', () => { callbacks.testTriggerOnce++; return 'foo'; });

      assert.strictEqual(eventbus.eventCount, 1);

      const promise = eventbus.triggerAsync('test:trigger:once');

      assert.strictEqual(eventbus.eventCount, 0);

      assert.strictEqual(callbacks.testTriggerOnce, 1);
      assert(promise instanceof Promise);

      const promise2 = eventbus.triggerAsync('test:trigger:once');

      assert.strictEqual(callbacks.testTriggerOnce, 1);
      assert(promise2 instanceof Promise);

      // triggerAsync resolves all Promises by Promise.all() or Promise.resolve() so result is a string.
      promise.then((result) =>
      {
         assert.strictEqual(callbacks.testTriggerOnce, 1);
         assert.strictEqual(result, 'foo');
         done();
      });
   });

   it('triggerAsync (listenTo)', (done) =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerCount = 0;

      test.listenTo(eventbus, 'test:trigger:async', () => { callbacks.testTriggerCount++; return 'foo'; });

      assert.strictEqual(eventbus.eventCount, 1);

      let promise = eventbus.triggerAsync('test:trigger:async');

      assert(promise instanceof Promise);

      promise.then((result) =>
      {
         assert.strictEqual(callbacks.testTriggerCount, 1);
         assert.strictEqual(result, 'foo');
      });

      test.stopListening(eventbus, 'test:trigger:async');

      assert.strictEqual(eventbus.eventCount, 0);

      promise = eventbus.triggerAsync('test:trigger:async');

      promise.then((result) =>
      {
         assert.isUndefined(result);
         assert.strictEqual(callbacks.testTriggerCount, 1);
         done();
      });
   });

   it('triggerAsync (listenToOnce)', (done) =>
   {
      const test = new TyphonEvents();

      callbacks.testTriggerOnce = 0;

      assert.strictEqual(eventbus.eventCount, 0);

      test.listenToOnce(eventbus, 'test:trigger:once', () => { callbacks.testTriggerOnce++; return 'foo'; });

      assert.strictEqual(eventbus.eventCount, 1);

      const promise = eventbus.triggerAsync('test:trigger:once');

      assert.strictEqual(eventbus.eventCount, 0);

      assert.strictEqual(callbacks.testTriggerOnce, 1);
      assert(promise instanceof Promise);

      const promise2 = eventbus.triggerAsync('test:trigger:once');

      assert.strictEqual(callbacks.testTriggerOnce, 1);
      assert(promise2 instanceof Promise);

      // triggerAsync resolves all Promises by Promise.all() or Promise.resolve() so result is a string.
      promise.then((result) =>
      {
         assert.strictEqual(callbacks.testTriggerOnce, 1);
         assert.strictEqual(result, 'foo');
         done();
      });
   });
});<|endoftext|>


<commit_before>/**
 * Canonicalize the message header according to
 * methods defined in RFC[XXXX]
 * @memberOf DKIM
 * @param {Buffer|String} header
 * @param {Array} signHeaders
 * @param {String} method - (simple|relaxed)
 * @return {String}
 * @throws {Error} If canonicalization method is unsupported
 */
function processHeader( headers, signHeaders, method ) {

  if( typeof signHeaders === 'string' ) {
    method = signHeaders
    signHeaders = null
  }

  method = method || 'simple'

  if( method !== 'simple' && method !== 'relaxed' ) {
    throw new Error( 'Canonicalization method "' + method + '" not supported' )
  }

  if( signHeaders != null ) {
    signHeaders = signHeaders.map( function( header ) {
      return header.toLowerCase()
    })
    headers = headers.filter( function( header ) {
      var key = header.slice( 0, header.indexOf( ':' ) ).trim().toLowerCase()
      return signHeaders.indexOf( key ) !== -1
    })
  }

  if( method === 'simple' ) {
    return headers.join( '\r\n' )
  }

  // TODO: Something's not right here...
  // relaxed signatures still don't verify
  if( method === 'relaxed' ) {
    return headers.map( function( line ) {

      var lines = {}
      var colon = line.indexOf( ':' )
      var value = line.slice( colon )

      // Convert all header field names to lowercase
      var key = line.slice( 0, colon ).toLowerCase()

      // Unfold all header field continuation lines
      value = value.replace( /\r\n(?=[\x20\x09])/g, '' )
      // Convert all sequences of one or more WSP characters to a single SP
      value = value.replace( /[\x20\x09]+/g, ' ' )
      // Delete all WSP characters at the end of each unfolded header field
      value = value.replace( /[\x20\x09]+$/g, '' )

      // Delete any WSP characters remaining before and after the colon
      return ( key + value ).replace( /[\x20\x09]*[:][\x20\x09]*/, ':' )

    }).join( '\r\n' )
  }

}

module.exports = processHeader
<commit_msg>append dkim signature at the end of the signing header message<commit_after>/**
 * Canonicalize the message header according to
 * methods defined in RFC[XXXX]
 * @memberOf DKIM
 * @param {Buffer|String} header
 * @param {Array} signHeaders
 * @param {String} method - (simple|relaxed)
 * @return {String}
 * @throws {Error} If canonicalization method is unsupported
 */
function processHeader( headers, signHeaders, method ) {

  if( typeof signHeaders === 'string' ) {
    method = signHeaders
    signHeaders = null
  }

  method = method || 'simple'

  if( method !== 'simple' && method !== 'relaxed' ) {
    throw new Error( 'Canonicalization method "' + method + '" not supported' )
  }

  if( signHeaders != null ) {

    // https://tools.ietf.org/html/rfc5322#section-3.6
    signHeaders = signHeaders.slice() // clone this array so that newely added headers don't show up outsite this "processHeader" function
    signHeaders.push('DKIM-Signature')
    signHeaders.push('X-Google-DKIM-Signature')

    signHeaders = signHeaders.map( function( header ) {
      return header.toLowerCase()
    })
    headers = headers.filter( function( header ) {
      var key = header.slice( 0, header.indexOf( ':' ) ).trim().toLowerCase()
      return signHeaders.indexOf( key ) !== -1
    })
  }

  if( method === 'simple' ) {
    return headers.join( '\r\n' )
  }

  // TODO: Something's not right here...
  // relaxed signatures still don't verify
  if( method === 'relaxed' ) {
    return headers.map( function( line ) {

      var lines = {}
      var colon = line.indexOf( ':' )
      var value = line.slice( colon )

      // Convert all header field names to lowercase
      var key = line.slice( 0, colon ).toLowerCase()

      // Unfold all header field continuation lines
      value = value.replace( /\r\n(?=[\x20\x09])/g, '' )
      // Convert all sequences of one or more WSP characters to a single SP
      value = value.replace( /[\x20\x09]+/g, ' ' )
      // Delete all WSP characters at the end of each unfolded header field
      value = value.replace( /[\x20\x09]+$/g, '' )

      // Delete signature value for "dkim-signature" header
      if(key === 'dkim-signature')
        value = value.replace( / b=(.*)$/, ' b=' )

      // Delete any WSP characters remaining before and after the colon
      return ( key + value ).replace( /[\x20\x09]*[:][\x20\x09]*/, ':' )

    }).join( '\r\n' )
  }

}

module.exports = processHeader
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const merge = require('deepmerge');

const loadAndParse = require('./loadAndParse');

// Import symbol key.
const IMPORT_SYMBOL = '~import';

/**
 * Constructs a circular imports error.
 *
 * @param  {string} fileBeingImported
 * The file being imported.
 *
 * @param  {string} importingFile
 * The file that imported.
 *
 * @return {Error}
 * An error.
 */
function circularImportsError(fileBeingImported, importTrail) {
  const message = `Circular import of "${fileBeingImported}".\r\n`
    + 'Import trace:\r\n'
    + importTrail.map(f => ` -> ${f}`).join('\r\n');
  return new Error(message);
}

/**
 * Processes import statements.
 *
 * @param  {object} obj
 * The object to process imports on.
 *
 * @param  {object} opts
 * Options.
 *
 * @param {string} opts.importingFile
 * Required! Used to base import cwd's.
 *
 * @return {object}
 * The merged sections
 */
module.exports = function processImports(parsed, opts) {
  opts.__loadedFiles = opts.__loadedFiles || [];
  opts.__importTrail = opts.__importTrail || [];

  opts.__loadedFiles.push(opts.importingFile);
  opts.__importTrail.unshift(opts.importingFile);

  // Helper to check if we have already loaded the given file.
  const hasLoadedFile = f => opts.__loadedFiles.indexOf(f) > -1;

  const imports = parsed[IMPORT_SYMBOL];
  if (!imports) return parsed;

  const filesToImport = [].concat(imports).map(
    f => path.resolve(path.dirname(opts.importingFile), f)
  );

  let processed = parsed;
  filesToImport.forEach(p => {
    delete processed[IMPORT_SYMBOL];
    if (hasLoadedFile(p)) throw circularImportsError(p, opts.__importTrail);
    const loaded = loadAndParse(p);
    const loadedAndProcessed = processImports(
      loaded,
      Object.assign(
        {},
        opts,
        {
          importingFile: p,
          __importTrail: opts.__importTrail.concat([])
        }
      )
    );

    processed = merge(loadedAndProcessed, processed);
  });

  return processed;
};<commit_msg>Added some comments.<commit_after>'use strict';

const path = require('path');
const merge = require('deepmerge');

const loadAndParse = require('./loadAndParse');

// Import symbol key.
const IMPORT_SYMBOL = '~import';

/**
 * Constructs a circular imports error.
 *
 * @param  {string} fileBeingImported
 * The file being imported.
 *
 * @param  {string} importingFile
 * The file that imported.
 *
 * @return {Error}
 * An error.
 */
function circularImportsError(fileBeingImported, importTrail) {
  const message = `Circular import of "${fileBeingImported}".\r\n`
    + 'Import trace:\r\n'
    + importTrail.map(f => ` -> ${f}`).join('\r\n');
  return new Error(message);
}

/**
 * Processes import statements.
 *
 * @param  {object} obj
 * The object to process imports on.
 *
 * @param  {object} opts
 * Options.
 *
 * @param {string} opts.importingFile
 * Required! Used to base import cwd's.
 *
 * @return {object}
 * The merged sections
 */
module.exports = function processImports(parsed, opts) {
  opts.__loadedFiles = opts.__loadedFiles || [];
  opts.__importTrail = opts.__importTrail || [];

  opts.__loadedFiles.push(opts.importingFile);
  opts.__importTrail.unshift(opts.importingFile);

  // Helper to check if we have already loaded the given file.
  const hasLoadedFile = f => opts.__loadedFiles.indexOf(f) > -1;

  const imports = parsed[IMPORT_SYMBOL];
  if (!imports) return parsed;

  const filesToImport = [].concat(imports).map(
    f => path.resolve(path.dirname(opts.importingFile), f)
  );

  let processed = parsed;
  filesToImport.forEach(p => {
    delete processed[IMPORT_SYMBOL];

    // Check for circular imports.
    if (hasLoadedFile(p)) throw circularImportsError(p, opts.__importTrail);
    const loaded = loadAndParse(p);
    const loadedAndProcessed = processImports(
      loaded,
      Object.assign(
        {},
        opts,
        {
          // The importing file is now the one being processed.
          importingFile: p,
          // We have to create a new import trail
          // based on the current one.
          __importTrail: opts.__importTrail.concat([])
        }
      )
    );

    // Deep merge them together, the outermost one winning.
    processed = merge(loadedAndProcessed, processed);
  });

  return processed;
};<|endoftext|>


<commit_before>var env = process.env;
var fs = require('fs');
var gzip = require('zlib').gzip;
var cache = require(env.Z_PATH_CACHE + 'cache');
var client;
var resHeaders = {
    'Cache-Control': 'public, max-age=31536000',
    'Vary': 'Accept-Encoding',
    'Content-Type': 'text/html; charset=utf-8',
    'Content-Encoding': 'gzip'
};

var publicCache = cache.file('public');

// get libs array
function getLibs (callback) {
    fs.exists(env.Z_CLIENT_LIBS, function (exists) {
        if (exists) {
            fs.readFile(env.Z_CLIENT_LIBS, function (err, data) {

                if (err) {
                    return callback(err);
                }

                // parse json file and save object in cache
                try {
                    data = JSON.parse(data);
                } catch (err) {
                    return callback(err);
                }

                callback(null, data);
            });

        // handle no libs
        } else {
            callback();
        }
    });
}

function sendClient (res) {

    if (client) {
        res.writeHead(200, resHeaders);
        return res.end(client);
    }

    // get libs paths
    getLibs(function (err, libs) {

        var lib_src = '';
        if (libs) {
            for (var i = 0; i < libs.length; ++i) {
                lib_src += "\n";
            }
        }

        gzip(
            "<!DOCTYPE html><link rel='icon' href='/favicon.ico'/>" +
            "" +
                lib_src +
                "" +
            "",
            function (err, data) {

                client = data;
                resHeaders['Content-Length'] = client.length;
                res.writeHead(200, resHeaders);
                res.end(client);
            }
        );
    });
}

function route (pathname, req, res) {
    var self = this;

    // send client
    if (pathname === '/') {
        return sendClient(res);
    }

    pathname = env.Z_PATH_PROCESS_PUBLIC + pathname;

    var file = publicCache.get(pathname);
    if (file) {
        res.writeHead(200, file.http);
        res.end(file.data);
        return;
    }

    publicCache.set(pathname, function (err, file) {

        if (err) {
            return sendClient(res);
        }

        res.writeHead(200, file.http);
        res.end(file.data);
    });
}

module.exports = route;
<commit_msg>comp cache method "set" checks also the internal cache<commit_after>var env = process.env;
var fs = require('fs');
var gzip = require('zlib').gzip;
var cache = require(env.Z_PATH_CACHE + 'cache');
var client;
var resHeaders = {
    'Cache-Control': 'public, max-age=31536000',
    'Vary': 'Accept-Encoding',
    'Content-Type': 'text/html; charset=utf-8',
    'Content-Encoding': 'gzip'
};

var publicCache = cache.file('public');

// get libs array
function getLibs (callback) {
    fs.exists(env.Z_CLIENT_LIBS, function (exists) {
        if (exists) {
            fs.readFile(env.Z_CLIENT_LIBS, function (err, data) {

                if (err) {
                    return callback(err);
                }

                // parse json file and save object in cache
                try {
                    data = JSON.parse(data);
                } catch (err) {
                    return callback(err);
                }

                callback(null, data);
            });

        // handle no libs
        } else {
            callback();
        }
    });
}

function sendClient (res) {

    if (client) {
        res.writeHead(200, resHeaders);
        return res.end(client);
    }

    // get libs paths
    getLibs(function (err, libs) {

        var lib_src = '';
        if (libs) {
            for (var i = 0; i < libs.length; ++i) {
                lib_src += "\n";
            }
        }

        gzip(
            "<!DOCTYPE html><link rel='icon' href='/favicon.ico'/>" +
            "" +
                lib_src +
                "" +
            "",
            function (err, data) {

                client = data;
                resHeaders['Content-Length'] = client.length;
                res.writeHead(200, resHeaders);
                res.end(client);
            }
        );
    });
}

function route (pathname, req, res) {
    var self = this;

    // send client
    if (pathname === '/') {
        return sendClient(res);
    }

    publicCache.set(env.Z_PATH_PROCESS_PUBLIC + pathname, function (err, file) {

        if (err) {
            return sendClient(res);
        }

        res.writeHead(200, file.http);
        res.end(file.data);
    });
}

module.exports = route;
<|endoftext|>


<commit_before>'use strict'

// dependencies
var Property = require('vigour-element/lib/property')

// shared
var SharedProperty = new Property({
  prefix: 'ui',
  old: {},
  on: {
    value (data, event) {
      let parent = this.parent
      let val = this.val
      if (parent) {
        let oldVal = this.old.val
        let prefix = this.prefix.val
        let element = parent.parent

        element.set({
          css: {
            removeClass: `${prefix}-${oldVal}`,
            addClass: `${prefix}-${val}`
          }
        })
      }
      this.old.set(val, event)
    }
  }
}).Constructor

// addition for scheme property
var SchemeProperty = new SharedProperty({
  prefix: 'ui-scheme'
}).Constructor

// addition for color property
var ColorProperty = new SharedProperty({
  prefix: 'ui-color'
}).Constructor

// addition for background property
var BackgroundProperty = new SharedProperty({
  prefix: 'ui-background'
}).Constructor

// addition for position property
var PositionProperty = new SharedProperty({
  prefix: 'ui-position'
}).Constructor

// addition for position property
var FontProperty = new SharedProperty({
  prefix: 'ui-font'
}).Constructor

// addition for hover property
var HoverProperty = new SharedProperty({
  prefix: 'ui-interactive ui-hover'
}).Constructor

// addition for hover property
var AnimationProperty = new SharedProperty({
  prefix: 'ui-animate ui'
}).Constructor

exports.properties = {
  /**
   * Use specific properties for UI classes.
   * Please use it without 'ui-' prefix.
   * It applies as `ui-{propertyname}` by default.
   */
  ui: new Property({
    properties: {
      /**
       * Name of component
       * @example
       * ui: {
       *   name: 'select'
       * }
       */
      name: SharedProperty,

      /**
       * Color classes. It applies as `ui-color-{colorname}`
       * @example
       * ui: {
       *   color: 'primary'
       * }
       */
      color: ColorProperty,

      /**
       * Background classes. It applies as `ui-background-{colorname}`
       * @example
       * ui: {
       *   scheme: 'primary'
       * }
       */
      background: BackgroundProperty,

      /**
       * Color specific classes
       * @example
       * ui: {
       *   scheme: 'primary'
       * }
       */
      scheme: SchemeProperty,

      /**
       * Size specific classes
       * @example
       * ui: {
       *   size: 'large'
       * }
       */
      size: SharedProperty,

      /**
       * Position specific classes
       * @example
       * ui: {
       *   position: 'vertically-center'
       * }
       */
      position: PositionProperty,

      /**
       * Specific type
       * @example
       * ui: {
       *   type: 'iconic'
       * }
       */
      type: SharedProperty,

      /**
       * Specific font
       * @example
       * ui: {
       *   font: 'bold'
       * }
       */
      font: FontProperty,

      /**
       * State specific classes
       * @example
       * ui: {
       *   state: 'dirty'
       * }
       */
      state: SharedProperty,

      /**
       * State specific classes
       * @example
       * ui: {
       *   atomic: 'molecule'
       * }
       */
      atomic: SharedProperty,

      /**
       * Text alignment
       * @example
       * ui: {
       *   atomic: 'molecule'
       * }
       */
      align: SharedProperty,

      /**
       * Set if it belongs to specific group of components
       * @example
       * ui: {
       *   childOf: 'form-element'
       * }
       */
      childOf: SharedProperty,

      /**
       * Set hover and focus effects by adding interactivity
       * @example
       * ui: {
       *   interactive: true
       * }
       */
      interactive: new Property({
        on: {
          value () {
            var element = this.parent.parent
            var val = this.val
            if (val) {
              element.set({
                css: {
                  addClass: 'ui-interactive'
                }
              })
            } else {
              element.set({
                css: {
                  removeClass: 'ui-interactive'
                }
              })
            }
          }
        }
      }),

      /**
       * Inverse colorset
       * @example
       * ui: {
       *   inverse: true
       * }
       */
      inverse: new Property({
        on: {
          value () {
            var element = this.parent.parent
            var val = this.val

            if (val) {
              element.set({
                css: {
                  addClass: 'ui-inverse'
                }
              })
            } else {
              element.set({
                css: {
                  removeClass: 'ui-inverse'
                }
              })
            }
          }
        }
      }),

      /**
       * Hover effects
       * @example
       * ui: {
       *   hover: 'zoom-in'
       * }
       */
      hover: HoverProperty,

      /**
       * Animation effects
       * @example
       * ui: {
       *   animate: 'fade-in-down'
       * }
       */
      animate: AnimationProperty
    }
  })
}
<commit_msg>added disabled property<commit_after>'use strict'

// dependencies
var Property = require('vigour-element/lib/property')

// shared
var SharedProperty = new Property({
  prefix: 'ui',
  old: {},
  on: {
    value (data, event) {
      let parent = this.parent
      let val = this.val
      if (parent) {
        let oldVal = this.old.val
        let prefix = this.prefix.val
        let element = parent.parent

        element.set({
          css: {
            removeClass: `${prefix}-${oldVal}`,
            addClass: `${prefix}-${val}`
          }
        })
      }
      this.old.set(val, event)
    }
  }
}).Constructor

// addition for scheme property
var SchemeProperty = new SharedProperty({
  prefix: 'ui-scheme'
}).Constructor

// addition for color property
var ColorProperty = new SharedProperty({
  prefix: 'ui-color'
}).Constructor

// addition for background property
var BackgroundProperty = new SharedProperty({
  prefix: 'ui-background'
}).Constructor

// addition for position property
var PositionProperty = new SharedProperty({
  prefix: 'ui-position'
}).Constructor

// addition for position property
var FontProperty = new SharedProperty({
  prefix: 'ui-font'
}).Constructor

// addition for hover property
var HoverProperty = new SharedProperty({
  prefix: 'ui-interactive ui-hover'
}).Constructor

// addition for hover property
var AnimationProperty = new SharedProperty({
  prefix: 'ui-animate ui'
}).Constructor

exports.properties = {
  /**
   * Use specific properties for UI classes.
   * Please use it without 'ui-' prefix.
   * It applies as `ui-{propertyname}` by default.
   */
  ui: new Property({
    properties: {
      /**
       * Name of component
       * @example
       * ui: {
       *   name: 'select'
       * }
       */
      name: SharedProperty,

      /**
       * Color classes. It applies as `ui-color-{colorname}`
       * @example
       * ui: {
       *   color: 'primary'
       * }
       */
      color: ColorProperty,

      /**
       * Background classes. It applies as `ui-background-{colorname}`
       * @example
       * ui: {
       *   scheme: 'primary'
       * }
       */
      background: BackgroundProperty,

      /**
       * Color specific classes
       * @example
       * ui: {
       *   scheme: 'primary'
       * }
       */
      scheme: SchemeProperty,

      /**
       * Size specific classes
       * @example
       * ui: {
       *   size: 'large'
       * }
       */
      size: SharedProperty,

      /**
       * Position specific classes
       * @example
       * ui: {
       *   position: 'vertically-center'
       * }
       */
      position: PositionProperty,

      /**
       * Specific type
       * @example
       * ui: {
       *   type: 'iconic'
       * }
       */
      type: SharedProperty,

      /**
       * Specific font
       * @example
       * ui: {
       *   font: 'bold'
       * }
       */
      font: FontProperty,

      /**
       * State specific classes
       * @example
       * ui: {
       *   state: 'dirty'
       * }
       */
      state: SharedProperty,

      /**
       * State specific classes
       * @example
       * ui: {
       *   atomic: 'molecule'
       * }
       */
      atomic: SharedProperty,

      /**
       * Text alignment
       * @example
       * ui: {
       *   atomic: 'molecule'
       * }
       */
      align: SharedProperty,

      /**
       * Set if it belongs to specific group of components
       * @example
       * ui: {
       *   childOf: 'form-element'
       * }
       */
      childOf: SharedProperty,

      /**
       * Set hover and focus effects by adding interactivity
       * @example
       * ui: {
       *   interactive: true
       * }
       */
      interactive: new Property({
        on: {
          value () {
            var element = this.parent.parent
            var val = this.val
            if (val) {
              element.set({
                css: {
                  addClass: 'ui-interactive'
                }
              })
            } else {
              element.set({
                css: {
                  removeClass: 'ui-interactive'
                }
              })
            }
          }
        }
      }),

      /**
       * Disable class for element and remove interactivity
       * @example
       * ui: {
       *   disable: true
       * }
       */
      disable: new Property({
        on: {
          value () {
            var element = this.parent.parent
            var val = this.val
            if (val) {
              element.set({
                css: {
                  addClass: 'ui-disable',
                  removeClass: 'ui-interactive'
                }
              })
            } else {
              if (element.ui && element.ui.interactive) {
                element.set({
                  css: {
                    addClass: 'ui-interactive',
                    removeClass: 'ui-disable'
                  }
                })

                return
              }

              element.set({
                css: {
                  removeClass: 'ui-disable'
                }
              })
            }
          }
        }
      }),

      /**
       * Inverse colorset
       * @example
       * ui: {
       *   inverse: true
       * }
       */
      inverse: new Property({
        on: {
          value () {
            var element = this.parent.parent
            var val = this.val

            if (val) {
              element.set({
                css: {
                  addClass: 'ui-inverse'
                }
              })
            } else {
              element.set({
                css: {
                  removeClass: 'ui-inverse'
                }
              })
            }
          }
        }
      }),

      /**
       * Hover effects
       * @example
       * ui: {
       *   hover: 'zoom-in'
       * }
       */
      hover: HoverProperty,

      /**
       * Animation effects
       * @example
       * ui: {
       *   animate: 'fade-in-down'
       * }
       */
      animate: AnimationProperty
    }
  })
}
<|endoftext|>


<commit_before>'use strict';

var
	path = require('path'),
	os = require('os');

var
	Promise = require('bluebird');

global.Promise = Promise;

var
	chai = require('chai'),
	chaiAsPromised = require('chai-as-promised'),
	merge = require('merge');

chai.should();
chai.use(chaiAsPromised);

global.expect = chai.expect;
global.all = Promise.all;
global.reject = Promise.reject;
global.resolve = Promise.resolve;
global.fs = Promise.promisifyAll(require('fs-extra'));
global.path = path;

// so that the env module uses the correct location
global.testHome = path.join(os.tmpdir(), 'enyo-dev');
global.testProj = path.join(testHome, 'proj');
global.testEmpty = path.join(testHome, 'empty');
global.testLink = path.join(testHome, 'linkable');
global.testLibs = path.join(testHome, 'test-libs');
global.testLibsPaths = [
	path.join(testLibs, 'lib1'),
	path.join(testLibs, 'more', 'lib2'),
	path.join(testLibs, 'more', 'lib3')
];

var
	env = require('../../lib/enyo/lib/env'),
	cli = global.cli = require('../../lib/cli-logger');

// we don't want to see output during testing
cli.stop();

global.getOpts = function (addl) {
	var def = {cwd: testHome};
	if (addl) def = merge(def, addl);
	return env(def);
};

var projConf, projPkg;

projConf = {
	name: 'testproject',
	libraries: [
		'enyo',
		'moonstone'
	],
	libDir: 'libdir',
	sources: {
		enyo: 'https://github.com/enyojs/enyo.git',
		moonstone: 'https://github.com/enyojs/moonstone.git'
	}
};

projPkg = {
	name: 'testproject',
	paths: [
		'lib'
	]
};

global.setupEnv = function () {
	return fs.ensureDirAsync(testHome).then(function () {
		return all([
			fs.ensureDirAsync(testEmpty),
			fs.ensureDirAsync(testProj).then(function () {
				return all([
					fs.writeJsonAsync(path.join(testProj, '.enyoconfig'), projConf, {spaces: 2}),
					fs.writeJsonAsync(path.join(testProj, 'package.json'), projPkg, {spaces: 2})
				])
			}),
			fs.ensureDirAsync(testLink)
		])
	});
};

global.setupLinks = function () {
	return all([
		createLinkable('test1'),
		createLinkable('test2'),
		createLinkable('test3')
	]);
};

global.setupTestLibs = function () {
	return fs.ensureDirAsync(testLibs).then(function () {
		return all(testLibsPaths.map(function (p) {
			return fs.ensureDirAsync(p).then(function () {
				return getOpts({cwd: p, library: true}).then(function (opts) {
					return require('../../lib/enyo/lib/init')(opts);
				});
			});
		}));
	});
};

function createLinkable(name) {
	return getOpts().then(function (opts) {
		var proj = path.join(testHome, name);
		return fs.ensureDirAsync(proj).then(function () {
			return fs.writeJsonAsync(path.join(proj, '.enyoconfig'), {name: name}).then(function () {
				return getOpts({cwd: proj}).then(function (opts) {
					return require('../../lib/enyo/lib/link')(opts);
				});
			});
		});
	});
}

global.cleanupEnv = function () {
	return fs.removeAsync(testHome);
};

global.resetEnv = function () {
	return fs.emptyDirAsync(testHome).then(function () {
		return setupEnv();
	});
};<commit_msg>allow tests to correctly compile for now as well<commit_after>'use strict';

require('babel/register')({
	extensions: ['.es6']
});

var
	path = require('path'),
	os = require('os');

var
	Promise = require('bluebird');

global.Promise = Promise;

var
	chai = require('chai'),
	chaiAsPromised = require('chai-as-promised'),
	merge = require('merge');

chai.should();
chai.use(chaiAsPromised);

global.expect = chai.expect;
global.all = Promise.all;
global.reject = Promise.reject;
global.resolve = Promise.resolve;
global.fs = Promise.promisifyAll(require('fs-extra'));
global.path = path;

// so that the env module uses the correct location
global.testHome = path.join(os.tmpdir(), 'enyo-dev');
global.testProj = path.join(testHome, 'proj');
global.testEmpty = path.join(testHome, 'empty');
global.testLink = path.join(testHome, 'linkable');
global.testLibs = path.join(testHome, 'test-libs');
global.testLibsPaths = [
	path.join(testLibs, 'lib1'),
	path.join(testLibs, 'more', 'lib2'),
	path.join(testLibs, 'more', 'lib3')
];

var
	env = require('../../lib/enyo/lib/env'),
	cli = global.cli = require('../../lib/cli-logger');

// we don't want to see output during testing
cli.stop();

global.getOpts = function (addl) {
	var def = {cwd: testHome};
	if (addl) def = merge(def, addl);
	return env(def);
};

var projConf, projPkg;

projConf = {
	name: 'testproject',
	libraries: [
		'enyo',
		'moonstone'
	],
	libDir: 'libdir',
	sources: {
		enyo: 'https://github.com/enyojs/enyo.git',
		moonstone: 'https://github.com/enyojs/moonstone.git'
	}
};

projPkg = {
	name: 'testproject',
	paths: [
		'lib'
	]
};

global.setupEnv = function () {
	return fs.ensureDirAsync(testHome).then(function () {
		return all([
			fs.ensureDirAsync(testEmpty),
			fs.ensureDirAsync(testProj).then(function () {
				return all([
					fs.writeJsonAsync(path.join(testProj, '.enyoconfig'), projConf, {spaces: 2}),
					fs.writeJsonAsync(path.join(testProj, 'package.json'), projPkg, {spaces: 2})
				])
			}),
			fs.ensureDirAsync(testLink)
		])
	});
};

global.setupLinks = function () {
	return all([
		createLinkable('test1'),
		createLinkable('test2'),
		createLinkable('test3')
	]);
};

global.setupTestLibs = function () {
	return fs.ensureDirAsync(testLibs).then(function () {
		return all(testLibsPaths.map(function (p) {
			return fs.ensureDirAsync(p).then(function () {
				return getOpts({cwd: p, library: true}).then(function (opts) {
					return require('../../lib/enyo/lib/init')(opts);
				});
			});
		}));
	});
};

function createLinkable(name) {
	return getOpts().then(function (opts) {
		var proj = path.join(testHome, name);
		return fs.ensureDirAsync(proj).then(function () {
			return fs.writeJsonAsync(path.join(proj, '.enyoconfig'), {name: name}).then(function () {
				return getOpts({cwd: proj}).then(function (opts) {
					return require('../../lib/enyo/lib/link')(opts);
				});
			});
		});
	});
}

global.cleanupEnv = function () {
	return fs.removeAsync(testHome);
};

global.resetEnv = function () {
	return fs.emptyDirAsync(testHome).then(function () {
		return setupEnv();
	});
};<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');

var app = express();

app.use(function(req, res, next) {
  res.set('Cache-Control', 'no-cache, no-store');
  next();
});

app.all('/url', function(req, res){
  res.send(req.url);
});

app.all('/echo', function(req, res){
  res.writeHead(200, req.headers);
  req.pipe(res);
});

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());

app.use('/xdomain', function(req, res, next){
  if (!req.get('Origin')) return next();
  res.set('Access-Control-Allow-Origin', req.get('Origin'));
  res.set('Access-Control-Allow-Credentials', 'true');
  res.set('Access-Control-Allow-Methods', 'POST');
  res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
  if ('OPTIONS' == req.method) return res.send(200);
  next();
});

app.get('/xdomain', function(req, res){
  res.send('tobi');
});

app.get('/login', function(req, res){
  res.status(200).send('<form id="login"></form>');
});

app.get('/json', function(req, res){
  res.status(200).json({ name: 'manny' });
});

app.get('/json-hal', function(req, res){
  res.set('content-type', 'application/hal+json');
  res.send({ name: 'hal 5000' });
});

app.get('/ok', function(req, res){
  res.send('ok');
});

app.get('/foo', function(req, res){
  res
    .header('Content-Type', 'application/x-www-form-urlencoded')
    .send('foo=bar');
});

app.get('/', function(req, res){
  res.redirect('/movies');
});

app.get('/movies', function(req, res){
  res.redirect('/movies/all');
});

app.get('/movies/all', function(req, res){
  res.redirect('/movies/all/0');
});

app.get('/movies/all/0', function(req, res){
  res.status(200).send('first movie page');
});

app.get('/links', function(req, res){
  res.header('Link', '<https://api.github.com/repos/visionmedia/mocha/issues?page=2>; rel="next"');
  res.end();
});

app.get('/xml', function(req, res){
  res.type('xml');
  res.status(200).send('<some><xml></xml></some>');
});

app.get('/custom', function(req, res){
  res.type('application/x-custom');
  res.status(200).send('custom stuff');
});

app.put('/user/:id', function(req, res){
  res.send('updated');
});

app.patch('/user/:id', function(req, res){
  res.send('updated');
});

app.post('/user/:id/pet', function(req, res){
  res.send('added pet "' + req.body.pet + '"');
});

app.post('/user', function(req, res){
  res.send('created');
});

app.delete('/user/:id', function(req, res){
  res.send('deleted');
});

app.post('/todo/item', function(req, res){
  var buf = '';
  req.on('data', function(chunk){ buf += chunk; });
  req.on('end', function(){
    res.send('added "' + buf + '"');
  });
});

app.get('/delay/const', function (req, res) {
  res.redirect('/delay/3000');
});

app.get('/delay/:ms', function(req, res){
  var ms = ~~req.params.ms;
  setTimeout(function(){
    res.sendStatus(200);
  }, ms);
});

app.get('/querystring', function(req, res){
  res.send(req.query);
});

app.get('/echo-header/:field', function(req, res){
  res.send(req.headers[req.params.field]);
});

app.post('/pet', function(req, res){
  res.send('added ' + req.body.name + ' the ' + req.body.species);
});

app.get('/pets', function(req, res){
  res.send(['tobi', 'loki', 'jane']);
});

app.get('/invalid-json', function(req, res) {
  res.set('content-type', 'application/json');
  // sample invalid json taken from https://github.com/swagger-api/swagger-ui/issues/1354
  res.send(")]}', {'header':{'code':200,'text':'OK','version':'1.0'},'data':'some data'}");
});

app.get('/invalid-json-forbidden', function(req, res) {
  res.set('content-type', 'application/json');
  res.status(403).send("Forbidden");
});

app.get('/text', function(req, res){
  res.send("just some text");
});

app.post('/auth', function(req, res) {
  var auth = req.headers.authorization,
      parts = auth.split(' '),
      credentials = new Buffer(parts[1], 'base64').toString().split(':'),
      user = credentials[0],
      pass = credentials[1];

  res.send({ user : user, pass : pass });
});

app.get('/error', function(req, res){
  res.status(500).send('boom');
});

app.get('/unauthorized', function(req, res){
  res.sendStatus(401);
});

app.get('/bad-request', function(req, res){
  res.sendStatus(400);
});

app.get('/not-acceptable', function(req, res){
  res.sendStatus(406);
});

app.get('/no-content', function(req, res){
  res.sendStatus(204);
});

app.delete('/no-content', function(req, res){
  res.set('content-type', 'application/json');
  res.sendStatus(204);
});

app.get('/arraybuffer', function(req, res) {
  var content = new ArrayBuffer(1000);
  res.set('Content-Type', 'application/vnd.superagent');
  res.send(content);
});

app.post('/empty-body', bodyParser.text(), function(req, res) {
  if (typeof req.body === 'object' && Object.keys(req.body).length === 0) {
    res.sendStatus(204);
  }
  else {
    res.sendStatus(400);
  }
});

app.get('/collection-json', function(req, res){
  res.set('content-type', 'application/vnd.collection+json');
  res.send({ name: 'chewbacca' });
});

app.get('/invalid-json', function(req, res) {
  res.set('content-type', 'application/json');
  // sample invalid json taken from https://github.com/swagger-api/swagger-ui/issues/1354
  res.send(")]}', {'header':{'code':200,'text':'OK','version':'1.0'},'data':'some data'}");
});

app.listen(process.env.ZUUL_PORT);
<commit_msg>fixed basic auth test<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var basicAuth = require('basic-auth-connect');

var app = express();

app.use(function(req, res, next) {
  res.set('Cache-Control', 'no-cache, no-store');
  next();
});

app.all('/url', function(req, res){
  res.send(req.url);
});

app.all('/echo', function(req, res){
  res.writeHead(200, req.headers);
  req.pipe(res);
});

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());

app.use('/xdomain', function(req, res, next){
  if (!req.get('Origin')) return next();
  res.set('Access-Control-Allow-Origin', req.get('Origin'));
  res.set('Access-Control-Allow-Credentials', 'true');
  res.set('Access-Control-Allow-Methods', 'POST');
  res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
  if ('OPTIONS' == req.method) return res.send(200);
  next();
});

app.get('/xdomain', function(req, res){
  res.send('tobi');
});

app.get('/login', function(req, res){
  res.status(200).send('<form id="login"></form>');
});

app.get('/json', function(req, res){
  res.status(200).json({ name: 'manny' });
});

app.get('/json-hal', function(req, res){
  res.set('content-type', 'application/hal+json');
  res.send({ name: 'hal 5000' });
});

app.get('/ok', function(req, res){
  res.send('ok');
});

app.get('/foo', function(req, res){
  res
    .header('Content-Type', 'application/x-www-form-urlencoded')
    .send('foo=bar');
});

app.get('/', function(req, res){
  res.redirect('/movies');
});

app.get('/movies', function(req, res){
  res.redirect('/movies/all');
});

app.get('/movies/all', function(req, res){
  res.redirect('/movies/all/0');
});

app.get('/movies/all/0', function(req, res){
  res.status(200).send('first movie page');
});

app.get('/links', function(req, res){
  res.header('Link', '<https://api.github.com/repos/visionmedia/mocha/issues?page=2>; rel="next"');
  res.end();
});

app.get('/xml', function(req, res){
  res.type('xml');
  res.status(200).send('<some><xml></xml></some>');
});

app.get('/custom', function(req, res){
  res.type('application/x-custom');
  res.status(200).send('custom stuff');
});

app.put('/user/:id', function(req, res){
  res.send('updated');
});

app.patch('/user/:id', function(req, res){
  res.send('updated');
});

app.post('/user/:id/pet', function(req, res){
  res.send('added pet "' + req.body.pet + '"');
});

app.post('/user', function(req, res){
  res.send('created');
});

app.delete('/user/:id', function(req, res){
  res.send('deleted');
});

app.post('/todo/item', function(req, res){
  var buf = '';
  req.on('data', function(chunk){ buf += chunk; });
  req.on('end', function(){
    res.send('added "' + buf + '"');
  });
});

app.get('/delay/const', function (req, res) {
  res.redirect('/delay/3000');
});

app.get('/delay/:ms', function(req, res){
  var ms = ~~req.params.ms;
  setTimeout(function(){
    res.sendStatus(200);
  }, ms);
});

app.get('/querystring', function(req, res){
  res.send(req.query);
});

app.get('/echo-header/:field', function(req, res){
  res.send(req.headers[req.params.field]);
});

app.post('/pet', function(req, res){
  res.send('added ' + req.body.name + ' the ' + req.body.species);
});

app.get('/pets', function(req, res){
  res.send(['tobi', 'loki', 'jane']);
});

app.get('/invalid-json', function(req, res) {
  res.set('content-type', 'application/json');
  // sample invalid json taken from https://github.com/swagger-api/swagger-ui/issues/1354
  res.send(")]}', {'header':{'code':200,'text':'OK','version':'1.0'},'data':'some data'}");
});

app.get('/invalid-json-forbidden', function(req, res) {
  res.set('content-type', 'application/json');
  res.status(403).send("Forbidden");
});

app.get('/text', function(req, res){
  res.send("just some text");
});

app.post('/auth', basicAuth('foo', 'bar'), function(req, res) {
  var auth = req.headers.authorization,
      parts = auth.split(' '),
      credentials = new Buffer(parts[1], 'base64').toString().split(':'),
      user = credentials[0],
      pass = credentials[1];

  res.send({ user : user, pass : pass });
});

app.get('/error', function(req, res){
  res.status(500).send('boom');
});

app.get('/unauthorized', function(req, res){
  res.sendStatus(401);
});

app.get('/bad-request', function(req, res){
  res.sendStatus(400);
});

app.get('/not-acceptable', function(req, res){
  res.sendStatus(406);
});

app.get('/no-content', function(req, res){
  res.sendStatus(204);
});

app.delete('/no-content', function(req, res){
  res.set('content-type', 'application/json');
  res.sendStatus(204);
});

app.get('/arraybuffer', function(req, res) {
  var content = new ArrayBuffer(1000);
  res.set('Content-Type', 'application/vnd.superagent');
  res.send(content);
});

app.post('/empty-body', bodyParser.text(), function(req, res) {
  if (typeof req.body === 'object' && Object.keys(req.body).length === 0) {
    res.sendStatus(204);
  }
  else {
    res.sendStatus(400);
  }
});

app.get('/collection-json', function(req, res){
  res.set('content-type', 'application/vnd.collection+json');
  res.send({ name: 'chewbacca' });
});

app.get('/invalid-json', function(req, res) {
  res.set('content-type', 'application/json');
  // sample invalid json taken from https://github.com/swagger-api/swagger-ui/issues/1354
  res.send(")]}', {'header':{'code':200,'text':'OK','version':'1.0'},'data':'some data'}");
});

app.listen(process.env.ZUUL_PORT);
<|endoftext|>


<commit_before>var test = require('tape');
var xtend = require('xtend');

var mapData = {
  version: 3,
  file: 'bars.js.map',
  sources: ['foo.js'],
  names: [],
  mappings: 'AAAA'
};

var mapBase64 = '# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmFycy5qcy5tYXAiLCJzb3VyY2VzIjpbImZvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSJ9';

var mapDataWithSourcesContent = xtend(mapData, {sourcesContent: ['0']});

var mapBase64WithSourcesContent = '# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmFycy5qcy5tYXAiLCJzb3VyY2VzIjpbImZvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZXNDb250ZW50IjpbIjAiXX0=';

module.exports =  function(options) {
  'use strict';

  var inlineSourceMapComment = options.main;

  test('inlineSourceMapComment on ' + options.environment, function(t) {

    t.plan(9);

    t.equal(
      inlineSourceMapComment(mapData),
      '//' + mapBase64,
      'should create a base64-encoded source map from an object.'
    );

    t.equal(
      inlineSourceMapComment(JSON.stringify(mapData)),
      '//' + mapBase64,
      'should create a base64-encoded source map from a string.'
    );

    t.notEqual(
      inlineSourceMapComment(Object.create(mapData)),
      '//' + mapBase64,
      'should ignore inherit properties.'
    );

    t.throws(
      function() {
        inlineSourceMapComment('');
      },
      /SyntaxError/,
      'should throw a syntax error when it takes non-JSON string.'
    );

    t.throws(
      function() {
        inlineSourceMapComment();
      },
      /More than one argument required/,
      'should throw a type error when it doesn\'t take any arguments.'
    );

    t.equal(
      inlineSourceMapComment(mapData, {block: true}),
      '/* ' + mapBase64 + ' */',
      'should create a block comment when `block` option is enabled.'
    );

    t.equal(
      inlineSourceMapComment(mapDataWithSourcesContent),
      '//' + mapBase64,
      'should remove `sourcesContent` property.'
    );

    t.equal(
      inlineSourceMapComment(mapDataWithSourcesContent, {sourcesContent: true}),
      '//' + mapBase64WithSourcesContent,
      'should preserve `sourcesContent` property when `sourcesContent` option is enabled.'
    );

    t.equal(
      inlineSourceMapComment.prefix,
      '# sourceMappingURL=data:application/json;base64,',
      'should have `prefix` property.'
    );
  });
};
<commit_msg>gurrantee not to modify first argument<commit_after>var test = require('tape');
var xtend = require('xtend');

var mapData = {
  version: 3,
  file: 'bars.js.map',
  sources: ['foo.js'],
  names: [],
  mappings: 'AAAA'
};

var mapBase64 = '# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmFycy5qcy5tYXAiLCJzb3VyY2VzIjpbImZvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSJ9';

var mapDataWithSourcesContent = xtend(mapData, {sourcesContent: ['0']});

var mapBase64WithSourcesContent = '# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmFycy5qcy5tYXAiLCJzb3VyY2VzIjpbImZvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZXNDb250ZW50IjpbIjAiXX0=';

module.exports =  function(options) {
  'use strict';

  var inlineSourceMapComment = options.main;

  test('inlineSourceMapComment on ' + options.environment, function(t) {

    t.plan(10);

    t.equal(
      inlineSourceMapComment(mapData),
      '//' + mapBase64,
      'should create a base64-encoded source map from an object.'
    );

    var newMapData = xtend({}, mapData);
    inlineSourceMapComment(newMapData, {sourcesContent: false});

    t.deepEqual(
      newMapData, mapData,
      'should not modify the object of its first argument.'
    );

    t.equal(
      inlineSourceMapComment(JSON.stringify(mapData)),
      '//' + mapBase64,
      'should create a base64-encoded source map from a string.'
    );

    t.notEqual(
      inlineSourceMapComment(Object.create(mapData)),
      '//' + mapBase64,
      'should ignore inherit properties.'
    );

    t.throws(
      function() {
        inlineSourceMapComment('');
      },
      /SyntaxError/,
      'should throw a syntax error when it takes non-JSON string.'
    );

    t.throws(
      function() {
        inlineSourceMapComment();
      },
      /More than one argument required/,
      'should throw a type error when it doesn\'t take any arguments.'
    );

    t.equal(
      inlineSourceMapComment(mapData, {block: true}),
      '/* ' + mapBase64 + ' */',
      'should create a block comment when `block` option is enabled.'
    );

    t.equal(
      inlineSourceMapComment(mapDataWithSourcesContent),
      '//' + mapBase64,
      'should remove `sourcesContent` property.'
    );

    t.equal(
      inlineSourceMapComment(mapDataWithSourcesContent, {sourcesContent: true}),
      '//' + mapBase64WithSourcesContent,
      'should preserve `sourcesContent` property when `sourcesContent` option is enabled.'
    );

    t.equal(
      inlineSourceMapComment.prefix,
      '# sourceMappingURL=data:application/json;base64,',
      'should have `prefix` property.'
    );
  });
};
<|endoftext|>