<commit_before>/**
 *
 * The Preloader state is used to preload assets before the MainMenu is displayed. Once assets have been loaded the Preloader state
 * will start the MainMenu state
 */

Game.Preloader = function(game) { };

Game.Preloader.prototype = {
    preload:function(){
        var preloadBG = this.add.sprite((this.world.width-580)*0.5, (this.world.height+150)*0.5, 'loading-background');
        var preloadProgress = this.add.sprite((this.world.width-540)*0.5, (this.world.height+170)*0.5, 'loading-progress');
        this.load.setPreloadSprite(preloadProgress);
        this.preloadResources();
        //this.load.script('webfont', '//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js');

    },
    preloadResources: function() {
        var pack = Game.Preloader.resources;

        for(var method in pack) {
            pack[method].forEach(function(args){
                var loader = this.load[method];
                loader && loader.apply(this.load, args);
            }, this);
        }

    },

    create:function(){
        this.state.start('MainMenu');
    }
};

Game.Preloader.resources = {
    /*
     * Load all game resources
     */
    'image' : [
        ['dot32', 'assets/img/dot32.png'],
        ['bigDot32', 'assets/img/bigDot32.png'],
        ['cTile32', 'assets/img/purpleTileset.png'],
        ['down', 'assets/img/down.png'],
        ['left', 'assets/img/left.png'],
        ['right', 'assets/img/right.png'],
        ['up', 'assets/img/up.png'],
        ['circle', 'assets/img/circle.png'],
        ['story-bg', 'assets/img/Packground.png'],
        ['bg-story', 'assets/img/StoryBackgroundBlur.png'],
        ['logo', 'assets/img/Logo.png'],
        ['instructions', 'assets/img/instructions.png'],
        ['overlay', 'assets/img/overlay.png'],
        ['ui-bg', 'assets/img/ui-bg.png'],
        ['particle', 'assets/img/particle.png'],
        ['black', 'assets/img/black.png'],
        ['cup', 'assets/img/trophy.png'],
        ['congrats', 'assets/img/congrats.png'],
        ['coupon-one', 'assets/img/dealercoupon.png'],
        ['coupon-two', 'assets/img/dealercoupontwo.png'],
        ['coupon-three', 'assets/img/dealercouponthree.png']

    ],

    'atlasXML': [
        ['spark', 'assets/atlasXML/spark.png', 'assets/atlasXML/spark.xml']
    ],

    'audio': [
        ['level_music', ['assets/audio/finalMainLoop.mp3', 'assets/audio/finalMainLoop.ogg']],
        ['menu_music', ['assets/audio/menuLoop.mp3', 'assets/audio/menuLoop.ogg']],
        ['big_eat_sfx', ['assets/audio/bigEat.mp3', 'assets/audio/bigEat.ogg']],
		['ghost_eat_sfx', ['assets/audio/ghostEat.mp3','assets/audio/ghostEat.ogg']],
		['lose', ['assets/audio/lose.mp3', 'assets/audio/lose.ogg']],
		['win', ['assets/audio/win.mp3', 'assets/audio/win.ogg']]
    ],

    'tilemap': [
        ['pmap32', 'assets/maps/pmap32.csv'],
        ['pmapdesk', 'assets/maps/pmapdesk.csv']

    ],

    'spritesheet': [
        ['csprites32','assets/img/chompersprites32.png', 32, 32],
        ['cSpTile32', 'assets/img/chompermazetiles32g.png', 32, 32],
        ['downs', 'assets/img/downs.png', 143,182],
        ['lefts', 'assets/img/lefts.png', 182, 143],
        ['rights', 'assets/img/rights.png', 182, 143],
        ['ups', 'assets/img/ups.png', 143,182],
        ['button-start', 'assets/img/button-start.png', 180, 180],
        ['button-rules', 'assets/img/rules-btn.png', 110, 40],
        ['button-play', 'assets/img/play-btn.png', 475, 140],
        ['button-continue', 'assets/img/button-continue.png', 180, 180],
        ['button-mainmenu', 'assets/img/button-mainmenu.png', 180, 180],
        ['button-restart', 'assets/img/button-tryagain.png', 180, 180],
        ['button-achievements', 'assets/img/button-achievements.png', 110, 110],
        ['button-pause', 'assets/img/button-pause.png', 80, 80],
        ['button-audio', 'assets/img/button-sound.png', 80, 80],
        ['button-back', 'assets/img/button-back.png', 70, 70],
        ['claim-prize-btn', 'assets/img/claimPrizes.png', 400, 60]

    ]

};
<commit_msg>change tilemap color<commit_after>/**
 *
 * The Preloader state is used to preload assets before the MainMenu is displayed. Once assets have been loaded the Preloader state
 * will start the MainMenu state
 */

Game.Preloader = function(game) { };

Game.Preloader.prototype = {
    preload:function(){
        var preloadBG = this.add.sprite((this.world.width-580)*0.5, (this.world.height+150)*0.5, 'loading-background');
        var preloadProgress = this.add.sprite((this.world.width-540)*0.5, (this.world.height+170)*0.5, 'loading-progress');
        this.load.setPreloadSprite(preloadProgress);
        this.preloadResources();
        //this.load.script('webfont', '//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js');

    },
    preloadResources: function() {
        var pack = Game.Preloader.resources;

        for(var method in pack) {
            pack[method].forEach(function(args){
                var loader = this.load[method];
                loader && loader.apply(this.load, args);
            }, this);
        }

    },

    create:function(){
        this.state.start('MainMenu');
    }
};

Game.Preloader.resources = {
    /*
     * Load all game resources
     */
    'image' : [
        ['dot32', 'assets/img/dot32.png'],
        ['bigDot32', 'assets/img/bigDot32.png'],
        ['cTile32', 'assets/img/chompermazetiles32g.png'],
        ['down', 'assets/img/down.png'],
        ['left', 'assets/img/left.png'],
        ['right', 'assets/img/right.png'],
        ['up', 'assets/img/up.png'],
        ['circle', 'assets/img/circle.png'],
        ['story-bg', 'assets/img/Packground.png'],
        ['bg-story', 'assets/img/StoryBackgroundBlur.png'],
        ['logo', 'assets/img/Logo.png'],
        ['instructions', 'assets/img/instructions.png'],
        ['overlay', 'assets/img/overlay.png'],
        ['ui-bg', 'assets/img/ui-bg.png'],
        ['particle', 'assets/img/particle.png'],
        ['black', 'assets/img/black.png'],
        ['cup', 'assets/img/trophy.png'],
        ['congrats', 'assets/img/congrats.png'],
        ['coupon-one', 'assets/img/dealercoupon.png'],
        ['coupon-two', 'assets/img/dealercoupontwo.png'],
        ['coupon-three', 'assets/img/dealercouponthree.png']

    ],

    'atlasXML': [
        ['spark', 'assets/atlasXML/spark.png', 'assets/atlasXML/spark.xml']
    ],

    'audio': [
        ['level_music', ['assets/audio/finalMainLoop.mp3', 'assets/audio/finalMainLoop.ogg']],
        ['menu_music', ['assets/audio/menuLoop.mp3', 'assets/audio/menuLoop.ogg']],
        ['big_eat_sfx', ['assets/audio/bigEat.mp3', 'assets/audio/bigEat.ogg']],
		['ghost_eat_sfx', ['assets/audio/ghostEat.mp3','assets/audio/ghostEat.ogg']],
		['lose', ['assets/audio/lose.mp3', 'assets/audio/lose.ogg']],
		['win', ['assets/audio/win.mp3', 'assets/audio/win.ogg']]
    ],

    'tilemap': [
        ['pmap32', 'assets/maps/pmap32.csv'],
        ['pmapdesk', 'assets/maps/pmapdesk.csv']

    ],

    'spritesheet': [
        ['csprites32','assets/img/chompersprites32.png', 32, 32],
        ['cSpTile32', 'assets/img/chompermazetiles32g.png', 32, 32],
        ['downs', 'assets/img/downs.png', 143,182],
        ['lefts', 'assets/img/lefts.png', 182, 143],
        ['rights', 'assets/img/rights.png', 182, 143],
        ['ups', 'assets/img/ups.png', 143,182],
        ['button-start', 'assets/img/button-start.png', 180, 180],
        ['button-rules', 'assets/img/rules-btn.png', 110, 40],
        ['button-play', 'assets/img/play-btn.png', 475, 140],
        ['button-continue', 'assets/img/button-continue.png', 180, 180],
        ['button-mainmenu', 'assets/img/button-mainmenu.png', 180, 180],
        ['button-restart', 'assets/img/button-tryagain.png', 180, 180],
        ['button-achievements', 'assets/img/button-achievements.png', 110, 110],
        ['button-pause', 'assets/img/button-pause.png', 80, 80],
        ['button-audio', 'assets/img/button-sound.png', 80, 80],
        ['button-back', 'assets/img/button-back.png', 70, 70],
        ['claim-prize-btn', 'assets/img/claimPrizes.png', 400, 60]

    ]

};
<|endoftext|>


<commit_before>/**
 * analytics.js - Provides an abstraction over code that calls Google Analytics
 * for user tracking. Attaches to router:navigation:success event to track when
 * a page has been loaded. Registers a click event handler for elements that are defined
 * in the filter function to track clicks.
 */

'use strict';

import {inject} from 'aurelia-dependency-injection';
import {EventAggregator} from 'aurelia-event-aggregator';
import * as LogManager from 'aurelia-logging';

/*
.plugin('aurelia-google-analytics', config => {
			config.init('<Tracker ID here>');
			config.attach({
				logging: {
					enabled: true
				},
				pageTracking: {
					enabled: true
				},
				clickTracking: {
					enabled: true,
					filter: () => {
						return element instanceof HTMLElement &&
						(element.nodeName.toLowerCase() === 'a' ||
							element.nodeName.toLowerCase() === 'button');
					}
				}
			});
		})
*/

const defaultOptions = {
	logging: {
		enabled: true
	},
	pageTracking: {
		enabled: false
	},
	clickTracking: {
		enabled: false
	}
};

const criteria = {
	isElement: function(e) { return e instanceof HTMLElement; },
	hasClass: function(cls) {
		return function(e) {
			return criteria.isElement(e) && e.classList.contains(cls);
		}
	},
	hasTrackingInfo: function(e) {
		return criteria.isElement(e) &&
			e.hasAttribute('data-analytics-category') &&
			e.hasAttribute('data-analytics-action');
	},
	isOfType: function(e, type) {
		return criteria.isElement(e) && e.nodeName.toLowerCase() === type.toLowerCase();
	},
	isAnchor: function(e) {
		return criteria.isOfType(e, 'a');
	},
	isButton: function(e) {
		return criteria.isOfType(e, 'button');
	}
};

const delegate = function(criteria, listener) {
	return function(evt) {
		let el = evt.target;
		do {
			if(!criteria(el)) continue;
			evt.delegateTarget = el;
			listener.apply(this, arguments);
			return;
		} while( (el = el.parentNode) );
	};
};

@inject(EventAggregator)
export class Analytics {
	constructor(eventAggregator) {
		this._eventAggregator = eventAggregator;
		this._initialized = false;
		this._logger = LogManager.getLogger('analytics-plugin');
		this._options = defaultOptions;

		this._trackClick = this._trackClick.bind(this);
		this._trackPage = this._trackPage.bind(this);
	}

	attach(options = defaultOptions) {
		this._options = Object.assign({}, defaultOptions, options);
		if(!this._initialized) {
			const errorMessage = "Analytics must be initialized before use.";
			this._log('error', errorMessage);
			throw new Error(errorMessage);
		}

		this._attachClickTracker();
		this._attachPageTracker();
	}

	init(id) {
		const script = document.createElement('script');
		script.text = "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){" +
			"(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o)," +
			"m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)" +
			"})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');";
		document.querySelector('body').appendChild(script);

		window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
		ga('create', id, 'auto');

		this._initialized = true;
	}

	_attachClickTracker() {
		if(!this._options.clickTracking.enabled) { return; }

		document.querySelector('body')
			.addEventListener('click', delegate(this._options.clickTracking.filter, this._trackClick));
	}

	_attachPageTracker() {
		if(!this._options.pageTracking.enabled) { return; }

		this._eventAggregator.subscribe('router:navigation:success',
			payload => this._trackPage(payload.instruction.fragment, payload.instruction.config.title));
	}

	_log(level, message) {
		if(!this._options.logging.enabled) { return; }

		this._logger[level](message);
	}

	_trackClick(evt) {
		if(!this._initialized) {
			this._log('warn', "The component has not been initialized. Please call 'init()' before calling 'attach()'.");
			return;
		}
		if(!evt || !evt.delegateTarget || !criteria.hasTrackingInfo(evt.delegateTarget)) { return };

		const element = evt.delegateTarget;
		const tracking = {
			category: element.getAttribute('data-analytics-category'),
			action: element.getAttribute('data-analytics-action'),
			label: element.getAttribute('data-analytics-label')
		};

		this._log('debug', `click: category '${tracking.category}', action '${tracking.action}', label '${tracking.label}'`);
		ga('send', 'event', tracking.category, tracking.action, tracking.label);
	}

	_trackPage(path, title) {
		this._log('debug', `Tracking path = ${path}, title = ${title}`);
		if(!this._initialized) {
			this._log('warn', "Try calling 'init()' before calling 'attach()'.");
			return;
		}

		ga('set', { page: path, title: title });
		ga('send', 'pageview');
	}
}
<commit_msg>Fix a null bug and add a default element filter.<commit_after>/**
 * analytics.js - Provides an abstraction over code that calls Google Analytics
 * for user tracking. Attaches to router:navigation:success event to track when
 * a page has been loaded. Registers a click event handler for elements that are defined
 * in the filter function to track clicks.
 */

'use strict';

import {inject} from 'aurelia-dependency-injection';
import {EventAggregator} from 'aurelia-event-aggregator';
import * as LogManager from 'aurelia-logging';

/*
.plugin('aurelia-google-analytics', config => {
			config.init('<Tracker ID here>');
			config.attach({
				logging: {
					enabled: true
				},
				pageTracking: {
					enabled: true
				},
				clickTracking: {
					enabled: true,
					filter: (element) => {
						return element instanceof HTMLElement &&
						(element.nodeName.toLowerCase() === 'a' ||
							element.nodeName.toLowerCase() === 'button');
					}
				}
			});
		})
*/

const defaultOptions = {
	logging: {
		enabled: true
	},
	pageTracking: {
		enabled: false
	},
	clickTracking: {
		enabled: false,
    filter: (element) => {
						return element instanceof HTMLElement &&
						(element.nodeName.toLowerCase() === 'a' ||
							element.nodeName.toLowerCase() === 'button');
					}
	}
};

const criteria = {
	isElement: function(e) { return e instanceof HTMLElement; },
	hasClass: function(cls) {
		return function(e) {
			return criteria.isElement(e) && e.classList.contains(cls);
		}
	},
	hasTrackingInfo: function(e) {
		return criteria.isElement(e) &&
			e.hasAttribute('data-analytics-category') &&
			e.hasAttribute('data-analytics-action');
	},
	isOfType: function(e, type) {
		return criteria.isElement(e) && e.nodeName.toLowerCase() === type.toLowerCase();
	},
	isAnchor: function(e) {
		return criteria.isOfType(e, 'a');
	},
	isButton: function(e) {
		return criteria.isOfType(e, 'button');
	}
};

const delegate = function(criteria, listener) {
	return function(evt) {
		let el = evt.target;
		do {
			if (criteria && !criteria(el))
        continue;
			evt.delegateTarget = el;
			listener.apply(this, arguments);
			return;
		} while( (el = el.parentNode) );
	};
};

@inject(EventAggregator)
export class Analytics {
	constructor(eventAggregator) {
		this._eventAggregator = eventAggregator;
		this._initialized = false;
		this._logger = LogManager.getLogger('analytics-plugin');
		this._options = defaultOptions;

		this._trackClick = this._trackClick.bind(this);
		this._trackPage = this._trackPage.bind(this);
	}

	attach(options = defaultOptions) {
		this._options = Object.assign({}, defaultOptions, options);
		if(!this._initialized) {
			const errorMessage = "Analytics must be initialized before use.";
			this._log('error', errorMessage);
			throw new Error(errorMessage);
		}

		this._attachClickTracker();
		this._attachPageTracker();
	}

	init(id) {
		const script = document.createElement('script');
		script.text = "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){" +
			"(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o)," +
			"m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)" +
			"})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');";
		document.querySelector('body').appendChild(script);

		window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
		ga('create', id, 'auto');

		this._initialized = true;
	}

	_attachClickTracker() {
		if(!this._options.clickTracking.enabled) { return; }

		document.querySelector('body')
			.addEventListener('click', delegate(this._options.clickTracking.filter, this._trackClick));
	}

	_attachPageTracker() {
		if(!this._options.pageTracking.enabled) { return; }

		this._eventAggregator.subscribe('router:navigation:success',
			payload => this._trackPage(payload.instruction.fragment, payload.instruction.config.title));
	}

	_log(level, message) {
		if(!this._options.logging.enabled) { return; }

		this._logger[level](message);
	}

	_trackClick(evt) {
		if(!this._initialized) {
			this._log('warn', "The component has not been initialized. Please call 'init()' before calling 'attach()'.");
			return;
		}
		if(!evt || !evt.delegateTarget || !criteria.hasTrackingInfo(evt.delegateTarget)) { return };

		const element = evt.delegateTarget;
		const tracking = {
			category: element.getAttribute('data-analytics-category'),
			action: element.getAttribute('data-analytics-action'),
			label: element.getAttribute('data-analytics-label')
		};

		this._log('debug', `click: category '${tracking.category}', action '${tracking.action}', label '${tracking.label}'`);
		ga('send', 'event', tracking.category, tracking.action, tracking.label);
	}

	_trackPage(path, title) {
		this._log('debug', `Tracking path = ${path}, title = ${title}`);
		if(!this._initialized) {
			this._log('warn', "Try calling 'init()' before calling 'attach()'.");
			return;
		}

		ga('set', { page: path, title: title });
		ga('send', 'pageview');
	}
}
<|endoftext|>


<commit_before>'use strict';

let log = require('intel'),
  Cookie = require('tough-cookie').Cookie,
  urlParser = require('url'),
  util = require('util'),
  moment = require('moment');

module.exports = {
  eventFromLogEntry: function(logEntry) {
    const logContent = JSON.parse(logEntry.message);

    return {
      timestamp: logEntry.timestamp,
      method: logContent.message.method,
      data: logContent.message.params,
      webview: logContent.webview
    }
  },
  harFromEvents: function(events) {
    function populateEntryFromResponse(entry, response, timestamp) {
      entry.response = {
        httpVersion: response.protocol,
        redirectURL: '',
        status: response.status,
        statusText: response.statusText,
        content: {
          mimeType: response.mimeType,
          size: 0
        },
        headersSize: -1,
        bodySize: -1,
        cookies: [],
        headers: parseHeaders(response.headers)
      };

      let locationHeaderValue = getHeaderValue(response.headers, 'Location');
      if (locationHeaderValue) {
        entry.response.redirectURL = locationHeaderValue;
      }

      entry.request.httpVersion = response.protocol;

      if (response.fromDiskCache === true && isHttp1x(response.protocol)) {
        entry.response.headersSize = calculateResponseHeaderSize(response);
      } else {
        if (response.requestHeaders) {
          entry.request.headers = parseHeaders(response.requestHeaders);

          const cookieHeader = getHeaderValue(response.requestHeaders, 'Cookie');
          entry.request.cookies = parseCookies(cookieHeader.split(';'));
        }

        if (isHttp1x(response.protocol)) {
          if (response.headersText) {
            entry.response.headersSize = response.headersText.length;
          } else {
            entry.response.headersSize = calculateResponseHeaderSize(response);
          }

          if (response.requestHeadersText) {
            entry.request.headersSize = response.requestHeadersText.length;
          } else {
            // Since entry.request.httpVersion is now set, we can calculate header size.
            entry.request.headersSize = calculateRequestHeaderSize(entry.request);
          }
        }
      }

      entry.connection = response.connectionId.toString();
      entry._connectionReused = response.connectionReused;

      let timing = response.timing;
      if (timing) {
        let blocked = firstNonNegative(timing["dnsStart"], timing["connectStart"], timing["sendStart"]);

        let dns = -1;
        if (timing["dnsStart"] >= 0) {
          dns = firstNonNegative([timing["connectStart"], timing["sendStart"]]) - timing["dnsStart"];
        }
        let connect = -1;
        if (timing["connectStart"] >= 0) {
          connect = timing["sendStart"] - timing["connectStart"];
        }
        let send = timing["sendEnd"] - timing["sendStart"];
        let wait = timing["receiveHeadersEnd"] - timing["sendEnd"];
        let receive = timestamp - timing["requestTime"];

        let ssl = -1;
        if (timing["sslStart"] >= 0 && timing["sslEnd"] >= 0) {
          ssl = timing["sslEnd"] - timing["sslStart"];
        }

        entry.timings = {
          blocked,
          dns,
          connect,
          send,
          wait,
          receive,
          ssl
        };

        entry._requestSentTime = timing["requestTime"];

        entry.time = ((blocked == -1) ? 0 : blocked) + ((dns == -1) ? 0 : dns) + ((connect == -1) ? 0 : connect) + send + wait + receive;

        //TODO: figure out how to correctly calculate blocking time
        let previousConnectionRequestId = previousConnectionIds.get(entry.connection);
        if (response.connectionReused && previousConnectionRequestId) {
          let previousEntry = entries.find((entry) => entry._requestId === previousConnectionRequestId);
          if (((entry._requestWillBeSentTime - previousEntry._requestWillBeSentTime) * 1000) < previousEntry.time) {
            entry.timings.blocked = previousEntry.time;
          }
        }

        entry.time += entry.timings.blocked;

      } else {
        entry.timings = {
          blocked: -1,
          dns: -1,
          connect: -1,
          send: 0,
          wait: 0,
          receive: 0,
          ssl: -1,
          comment: 'No timings available from Chrome'
        };
        entry.time = 0;
      }

      previousConnectionIds.set(entry.connection, entry._requestId);
    }

    let pages = [],
      entries = [],
      currentPageId,
      ongoingDataRequests = new Set(),
      previousConnectionIds = new Map(),
      rootFrameMappings = new Map();

    for (let event of events) {
      const data = event.data;
      switch (event.method) {
        case 'Page.frameStartedLoading':
        {
          const frameId = data.frameId;

          if (rootFrameMappings.has(frameId)) {
            // This is a sub frame, there's already a page for the root frame
            continue;
          }

          currentPageId = 'page_' + (pages.length + 1);
          let page = {
            id: currentPageId,
            startedDateTime: moment(event.timestamp).toISOString(),
            title: '',
            pageTimings: {},
            _frameId: data.frameId
          };
          pages.push(page);
        }
          break;

        case 'Network.requestWillBeSent':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue
          }
          const request = data.request;
          if (request.url.startsWith('data:')) {
            ongoingDataRequests.add(data.requestId);
            continue;
          }
          let frameId = rootFrameMappings.get(data.frameId) || data.frameId;
          let page = pages.find((page) => page._frameId === frameId);
          if (!page) {
            log.warn('Request will be sent with requestId ' + data.requestId + ' that can\'t be mapped to any page.');
            continue;
          }

          const cookieHeader = getHeaderValue(request.headers, 'Cookie');
          const cookies = parseCookies(cookieHeader.split(';'));

          let req = {
            method: request.method,
            url: request.url,
            _timestamp: data.timestamp,
            queryString: parsePostParams(request.url),
            headersSize: -1,
            bodySize: -1,
            _initialPriority: request.initialPriority,
            cookies: cookies,
            headers: parseHeaders(request.headers)
          };

          let entry = {
            cache: {},
            startedDateTime: moment.unix(data.wallTime).toISOString(), //epoch float64, eg 1440589909.59248
            _requestWillBeSentTime: data.timestamp,
            _wallTime: data.wallTime,
            _requestId: data.requestId,
            _frameId: data.frameId,
            pageref: currentPageId,
            request: req,
            time: 0
          };

          if (data.redirectResponse) {
            let previousEntry = entries.find((entry) => entry._requestId === data.requestId);
            previousEntry._requestId += 'r';
            populateEntryFromResponse(previousEntry, data.redirectResponse, data.timestamp);
          }

          entries.push(entry);

          // this is the first request for this page, so set timestamp of page.
          if (!page._timestamp) {
            page._wallTime = data.wallTime;
            page._timestamp = data.timestamp;
            page.startedDateTime = entry.startedDateTime;
            // URL is better than blank, and it's what devtools uses.
            page.title = request.url;
          }
        }
          break;

        case 'Network.responseReceived':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue
          }
          if (data.response.url.startsWith('data:')) {
            continue;
          }

          let entry = entries.find((entry) => entry._requestId === data.requestId);
          if (!entry) {
            log.warn('Recieved network response for requestId ' + data.requestId + ' with no matching request.');
            continue;
          }
          entry._responseReceivedTime = data.timestamp;
          entry._totalRequestTime = (data.timestamp - entry._requestWillBeSentTime) * 1000;

          try {
            populateEntryFromResponse(entry, data.response, data.timestamp);
          } catch (e) {
            log.error('Error parsing response: ' + JSON.stringify(data, null, 2));
            throw e;
          }
        }
          break;

        case 'Network.dataReceived':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue
          }
          if (ongoingDataRequests.has(data.requestId)) {
            continue;
          }

          let entry = entries.find((entry) => entry._requestId === data.requestId);
          if (!entry) {
            log.warn('Recieved network data for requestId ' + data.requestId + ' with no matching request.');
            continue;
          }

          entry._dataReceivedTime = entry._responseReceivedTime;
          entry.response.content.size += data.dataLength;
        }
          break;

        case 'Network.loadingFinished':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue
          }
          if (ongoingDataRequests.has(data.requestId)) {
            ongoingDataRequests.delete(data.requestId);
            continue;
          }

          let entry = entries.find((entry) => entry._requestId === data.requestId);
          if (!entry) {
            log.warn('Network loading finished for requestId ' + data.requestId + ' with no matching request.');
            continue;
          }

          entry._loadingFinishedTime = data.timestamp;
          entry.response.bodySize = entry.response.content.size;
          //if (entry.response.headersSize > -1) {
          //  entry.response.bodySize -= entry.response.headersSize;
          //}

          // encodedDataLength will be -1 sometimes
          if (data.encodedDataLength > 0) {
            // encodedDataLength seems to be larger than body size sometimes. Perhaps it's because full packets are
            // listed even though the actual data might be very small.
            // I've seen dataLength: 416, encodedDataLength: 1016,

            const compression = Math.max(0, entry.response.bodySize - data.encodedDataLength);
            if (compression > 0) {
              entry.response.content.compression = compression;
            }
          }
        }
          break;

        case 'Page.loadEventFired':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue;
          }

          let page = pages[pages.length - 1];

          if (data.timestamp && page._timestamp) {
            page.pageTimings.onLoad = Number((data.timestamp - page._timestamp) * 1000)
          }
        }
          break;

        case 'Page.domContentEventFired':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue;
          }

          let page = pages[pages.length - 1];

          if (data.timestamp && page._timestamp) {
            page.pageTimings.onContentLoad = Number((data.timestamp - page._timestamp) * 1000)
          }
        }
          break;

        case 'Page.frameAttached':
        {
          let parentId = data.parentFrameId;

          rootFrameMappings.set(data.frameId, parentId);

          let grandParentId = rootFrameMappings.get(parentId);
          while (grandParentId) {
            rootFrameMappings.set(data.frameId, grandParentId);
            grandParentId = rootFrameMappings.get(grandParentId);
          }
        }
          break;

        case 'Page.frameScheduledNavigation':
        case 'Page.frameNavigated':
        case 'Page.frameStoppedLoading':
        case 'Page.frameClearedScheduledNavigation':
        case 'Page.frameDetached':
        case 'Page.frameResized':
          // ignore
          break;

        case 'Page.javascriptDialogOpening':
        case 'Page.javascriptDialogClosed':
        case 'Page.screencastFrame':
        case 'Page.screencastVisibilityChanged':
        case 'Page.colorPicked':
        case 'Page.interstitialShown':
        case 'Page.interstitialHidden':
          // ignore
          break;

        case 'Network.requestServedFromCache':
        case 'Network.loadingFailed':
          // FIXME, should not ignore these
          break;

        case 'Network.webSocketCreated':
        case 'Network.webSocketFrameSent':
        case 'Network.webSocketFrameError':
        case 'Network.webSocketFrameReceived':
        case 'Network.webSocketClosed':
        case 'Network.webSocketHandshakeResponseReceived':
        case 'Network.webSocketWillSendHandshakeRequest':
          // ignore, sadly HAR file format doesn't include web sockets
          break;

        case 'Network.eventSourceMessageReceived':
          // ignore
          break;

        default:
          log.warn('Unhandled event: ' + event.method);
          break;
      }
    }

    //Dirty sort since Javascript treats everything as strings
    entries.sort(function(a, b) {
      if (a._requestId.indexOf('r') > -1) return 0;
      let entryOne = parseFloat(a._requestId.split(".").join("0")) * 1000;
      let entryTwo = parseFloat(b._requestId.split(".").join("0")) * 1000;
      return entryOne - entryTwo;
    });

    entries = entries.filter((entry) => {
      // Page doesn't wait for favicon to load, and that's ok (for now).
      if (!entry.response && !entry.request.url.endsWith('.ico')) {
        log.warn('Entry without response!: ' + JSON.stringify(entry));
      }
      return entry.response;
    });

    return {
      log: {
        version: "1.2",
        creator: {"name": "Browsertime", "version": "1.0"},
        pages,
        entries
      }
    }
  }
};

function calculateRequestHeaderSize(harRequest) {
  let buffer = '';
  buffer = buffer.concat(util.format('%s %s %s\r\n', harRequest.method, harRequest.url, harRequest.httpVersion));

  const headerLines = harRequest.headers.map((header) => util.format('%s: %s\r\n', header.name, header.value));
  buffer = buffer.concat(headerLines.join(''));
  buffer = buffer.concat('\r\n');

  return buffer.length;
}

function calculateResponseHeaderSize(perflogResponse) {
  let buffer = '';
  buffer = buffer.concat(util.format('%s %d %s\r\n', perflogResponse.protocol, perflogResponse.status, perflogResponse.statusText));
  Object.keys(perflogResponse.headers).forEach((key) => {
    buffer = buffer.concat(util.format('%s: %s\r\n', key, perflogResponse.headers[key]));
  });
  buffer = buffer.concat('\r\n');

  return buffer.length;
}

function parseCookies(cookieStrings) {
  return cookieStrings.filter(Boolean).map((cookieString) => {
    let cookie = Cookie.parse(cookieString);
    if (!cookie) {
      log.warn("Invalid cookie - failed to parse value: " + cookieString);

      return null;
    }

    return {
      'name': cookie.key,
      'value': cookie.value,
      'path': cookie.path || undefined, // must be undefined, not null, to exclude empty path
      'domain': cookie.domain || undefined,  // must be undefined, not null, to exclude empty domain
      'expires': cookie.expires === 'Infinity' ? undefined : moment(cookie.expires).toISOString(),
      'httpOnly': cookie.httpOnly,
      'secure': cookie.secure
    };
  });
}

function parseHeaders(headers) {
  if (!headers) {
    return [];
  }
  return Object.keys(headers).map((key) => {
    return {
      name: key,
      value: headers[key]
    }
  });
}

function getHeaderValue(headers, header) {
  if (!headers) {
    return '';
  }
  // http header names are case insensitive
  const lowerCaseHeader = header.toLowerCase();
  const headerNames = Object.keys(headers);
  return headerNames.filter((key) => key.toLowerCase() === lowerCaseHeader)
      .map((key) => headers[key]).shift() || '';
}

function parsePostParams(text) {
  var paramList = [];
  var queryString = urlParser.parse(text, true).query;
  Object.keys(queryString).forEach(function(name) {
    var value = queryString[name];
    if (!Array.isArray(value))
      value = [value];
    value.forEach(function(v) {
      paramList.push(
        {
          "name": name,
          "value": v
          //                    "fileName": "example.pdf",
          //                    "contentType": "application/pdf",
        });
    });
  });
  return paramList;
}

function isHttp1x(version) {
  return version.toLowerCase().startsWith('http/1.')
}

function firstNonNegative(values) {
  for (var i = 0; i < values.length; ++i) {
    if (values[i] >= 0)
      return values[i];
  }
  return -1;
}
<commit_msg>Rewrite to avoid ?= operator.<commit_after>'use strict';

let log = require('intel'),
  Cookie = require('tough-cookie').Cookie,
  urlParser = require('url'),
  util = require('util'),
  moment = require('moment');

module.exports = {
  eventFromLogEntry: function(logEntry) {
    const logContent = JSON.parse(logEntry.message);

    return {
      timestamp: logEntry.timestamp,
      method: logContent.message.method,
      data: logContent.message.params,
      webview: logContent.webview
    }
  },
  harFromEvents: function(events) {
    function populateEntryFromResponse(entry, response, timestamp) {
      entry.response = {
        httpVersion: response.protocol,
        redirectURL: '',
        status: response.status,
        statusText: response.statusText,
        content: {
          mimeType: response.mimeType,
          size: 0
        },
        headersSize: -1,
        bodySize: -1,
        cookies: [],
        headers: parseHeaders(response.headers)
      };

      let locationHeaderValue = getHeaderValue(response.headers, 'Location');
      if (locationHeaderValue) {
        entry.response.redirectURL = locationHeaderValue;
      }

      entry.request.httpVersion = response.protocol;

      if (response.fromDiskCache === true && isHttp1x(response.protocol)) {
        entry.response.headersSize = calculateResponseHeaderSize(response);
      } else {
        if (response.requestHeaders) {
          entry.request.headers = parseHeaders(response.requestHeaders);

          const cookieHeader = getHeaderValue(response.requestHeaders, 'Cookie');
          entry.request.cookies = parseCookies(cookieHeader.split(';'));
        }

        if (isHttp1x(response.protocol)) {
          if (response.headersText) {
            entry.response.headersSize = response.headersText.length;
          } else {
            entry.response.headersSize = calculateResponseHeaderSize(response);
          }

          if (response.requestHeadersText) {
            entry.request.headersSize = response.requestHeadersText.length;
          } else {
            // Since entry.request.httpVersion is now set, we can calculate header size.
            entry.request.headersSize = calculateRequestHeaderSize(entry.request);
          }
        }
      }

      entry.connection = response.connectionId.toString();
      entry._connectionReused = response.connectionReused;

      let timing = response.timing;
      if (timing) {
        let blocked = firstNonNegative(timing["dnsStart"], timing["connectStart"], timing["sendStart"]);

        let dns = -1;
        if (timing["dnsStart"] >= 0) {
          dns = firstNonNegative([timing["connectStart"], timing["sendStart"]]) - timing["dnsStart"];
        }
        let connect = -1;
        if (timing["connectStart"] >= 0) {
          connect = timing["sendStart"] - timing["connectStart"];
        }
        let send = timing["sendEnd"] - timing["sendStart"];
        let wait = timing["receiveHeadersEnd"] - timing["sendEnd"];
        let receive = timestamp - timing["requestTime"];

        let ssl = -1;
        if (timing["sslStart"] >= 0 && timing["sslEnd"] >= 0) {
          ssl = timing["sslEnd"] - timing["sslStart"];
        }

        entry.timings = {
          blocked,
          dns,
          connect,
          send,
          wait,
          receive,
          ssl
        };

        entry._requestSentTime = timing["requestTime"];

        const max = Math.max;
        entry.time = max(0, blocked) + max(0, dns) + max(0, connect) + send + wait + receive;

        //TODO: figure out how to correctly calculate blocking time
        let previousConnectionRequestId = previousConnectionIds.get(entry.connection);
        if (response.connectionReused && previousConnectionRequestId) {
          let previousEntry = entries.find((entry) => entry._requestId === previousConnectionRequestId);
          if (((entry._requestWillBeSentTime - previousEntry._requestWillBeSentTime) * 1000) < previousEntry.time) {
            entry.timings.blocked = previousEntry.time;
          }
        }

        entry.time += entry.timings.blocked;

      } else {
        entry.timings = {
          blocked: -1,
          dns: -1,
          connect: -1,
          send: 0,
          wait: 0,
          receive: 0,
          ssl: -1,
          comment: 'No timings available from Chrome'
        };
        entry.time = 0;
      }

      previousConnectionIds.set(entry.connection, entry._requestId);
    }

    let pages = [],
      entries = [],
      currentPageId,
      ongoingDataRequests = new Set(),
      previousConnectionIds = new Map(),
      rootFrameMappings = new Map();

    for (let event of events) {
      const data = event.data;
      switch (event.method) {
        case 'Page.frameStartedLoading':
        {
          const frameId = data.frameId;

          if (rootFrameMappings.has(frameId)) {
            // This is a sub frame, there's already a page for the root frame
            continue;
          }

          currentPageId = 'page_' + (pages.length + 1);
          let page = {
            id: currentPageId,
            startedDateTime: moment(event.timestamp).toISOString(),
            title: '',
            pageTimings: {},
            _frameId: data.frameId
          };
          pages.push(page);
        }
          break;

        case 'Network.requestWillBeSent':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue
          }
          const request = data.request;
          if (request.url.startsWith('data:')) {
            ongoingDataRequests.add(data.requestId);
            continue;
          }
          let frameId = rootFrameMappings.get(data.frameId) || data.frameId;
          let page = pages.find((page) => page._frameId === frameId);
          if (!page) {
            log.warn('Request will be sent with requestId ' + data.requestId + ' that can\'t be mapped to any page.');
            continue;
          }

          const cookieHeader = getHeaderValue(request.headers, 'Cookie');
          const cookies = parseCookies(cookieHeader.split(';'));

          let req = {
            method: request.method,
            url: request.url,
            _timestamp: data.timestamp,
            queryString: parsePostParams(request.url),
            headersSize: -1,
            bodySize: -1,
            _initialPriority: request.initialPriority,
            cookies: cookies,
            headers: parseHeaders(request.headers)
          };

          let entry = {
            cache: {},
            startedDateTime: moment.unix(data.wallTime).toISOString(), //epoch float64, eg 1440589909.59248
            _requestWillBeSentTime: data.timestamp,
            _wallTime: data.wallTime,
            _requestId: data.requestId,
            _frameId: data.frameId,
            pageref: currentPageId,
            request: req,
            time: 0
          };

          if (data.redirectResponse) {
            let previousEntry = entries.find((entry) => entry._requestId === data.requestId);
            previousEntry._requestId += 'r';
            populateEntryFromResponse(previousEntry, data.redirectResponse, data.timestamp);
          }

          entries.push(entry);

          // this is the first request for this page, so set timestamp of page.
          if (!page._timestamp) {
            page._wallTime = data.wallTime;
            page._timestamp = data.timestamp;
            page.startedDateTime = entry.startedDateTime;
            // URL is better than blank, and it's what devtools uses.
            page.title = request.url;
          }
        }
          break;

        case 'Network.responseReceived':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue
          }
          if (data.response.url.startsWith('data:')) {
            continue;
          }

          let entry = entries.find((entry) => entry._requestId === data.requestId);
          if (!entry) {
            log.warn('Recieved network response for requestId ' + data.requestId + ' with no matching request.');
            continue;
          }
          entry._responseReceivedTime = data.timestamp;
          entry._totalRequestTime = (data.timestamp - entry._requestWillBeSentTime) * 1000;

          try {
            populateEntryFromResponse(entry, data.response, data.timestamp);
          } catch (e) {
            log.error('Error parsing response: ' + JSON.stringify(data, null, 2));
            throw e;
          }
        }
          break;

        case 'Network.dataReceived':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue
          }
          if (ongoingDataRequests.has(data.requestId)) {
            continue;
          }

          let entry = entries.find((entry) => entry._requestId === data.requestId);
          if (!entry) {
            log.warn('Recieved network data for requestId ' + data.requestId + ' with no matching request.');
            continue;
          }

          entry._dataReceivedTime = entry._responseReceivedTime;
          entry.response.content.size += data.dataLength;
        }
          break;

        case 'Network.loadingFinished':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue
          }
          if (ongoingDataRequests.has(data.requestId)) {
            ongoingDataRequests.delete(data.requestId);
            continue;
          }

          let entry = entries.find((entry) => entry._requestId === data.requestId);
          if (!entry) {
            log.warn('Network loading finished for requestId ' + data.requestId + ' with no matching request.');
            continue;
          }

          entry._loadingFinishedTime = data.timestamp;
          entry.response.bodySize = entry.response.content.size;
          //if (entry.response.headersSize > -1) {
          //  entry.response.bodySize -= entry.response.headersSize;
          //}

          // encodedDataLength will be -1 sometimes
          if (data.encodedDataLength > 0) {
            // encodedDataLength seems to be larger than body size sometimes. Perhaps it's because full packets are
            // listed even though the actual data might be very small.
            // I've seen dataLength: 416, encodedDataLength: 1016,

            const compression = Math.max(0, entry.response.bodySize - data.encodedDataLength);
            if (compression > 0) {
              entry.response.content.compression = compression;
            }
          }
        }
          break;

        case 'Page.loadEventFired':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue;
          }

          let page = pages[pages.length - 1];

          if (data.timestamp && page._timestamp) {
            page.pageTimings.onLoad = Number((data.timestamp - page._timestamp) * 1000)
          }
        }
          break;

        case 'Page.domContentEventFired':
        {
          if (pages.length < 1) {
            //we havent loaded any pages yet.
            continue;
          }

          let page = pages[pages.length - 1];

          if (data.timestamp && page._timestamp) {
            page.pageTimings.onContentLoad = Number((data.timestamp - page._timestamp) * 1000)
          }
        }
          break;

        case 'Page.frameAttached':
        {
          let parentId = data.parentFrameId;

          rootFrameMappings.set(data.frameId, parentId);

          let grandParentId = rootFrameMappings.get(parentId);
          while (grandParentId) {
            rootFrameMappings.set(data.frameId, grandParentId);
            grandParentId = rootFrameMappings.get(grandParentId);
          }
        }
          break;

        case 'Page.frameScheduledNavigation':
        case 'Page.frameNavigated':
        case 'Page.frameStoppedLoading':
        case 'Page.frameClearedScheduledNavigation':
        case 'Page.frameDetached':
        case 'Page.frameResized':
          // ignore
          break;

        case 'Page.javascriptDialogOpening':
        case 'Page.javascriptDialogClosed':
        case 'Page.screencastFrame':
        case 'Page.screencastVisibilityChanged':
        case 'Page.colorPicked':
        case 'Page.interstitialShown':
        case 'Page.interstitialHidden':
          // ignore
          break;

        case 'Network.requestServedFromCache':
        case 'Network.loadingFailed':
          // FIXME, should not ignore these
          break;

        case 'Network.webSocketCreated':
        case 'Network.webSocketFrameSent':
        case 'Network.webSocketFrameError':
        case 'Network.webSocketFrameReceived':
        case 'Network.webSocketClosed':
        case 'Network.webSocketHandshakeResponseReceived':
        case 'Network.webSocketWillSendHandshakeRequest':
          // ignore, sadly HAR file format doesn't include web sockets
          break;

        case 'Network.eventSourceMessageReceived':
          // ignore
          break;

        default:
          log.warn('Unhandled event: ' + event.method);
          break;
      }
    }

    //Dirty sort since Javascript treats everything as strings
    entries.sort(function(a, b) {
      if (a._requestId.indexOf('r') > -1) return 0;
      let entryOne = parseFloat(a._requestId.split(".").join("0")) * 1000;
      let entryTwo = parseFloat(b._requestId.split(".").join("0")) * 1000;
      return entryOne - entryTwo;
    });

    entries = entries.filter((entry) => {
      // Page doesn't wait for favicon to load, and that's ok (for now).
      if (!entry.response && !entry.request.url.endsWith('.ico')) {
        log.warn('Entry without response!: ' + JSON.stringify(entry));
      }
      return entry.response;
    });

    return {
      log: {
        version: "1.2",
        creator: {"name": "Browsertime", "version": "1.0"},
        pages,
        entries
      }
    }
  }
};

function calculateRequestHeaderSize(harRequest) {
  let buffer = '';
  buffer = buffer.concat(util.format('%s %s %s\r\n', harRequest.method, harRequest.url, harRequest.httpVersion));

  const headerLines = harRequest.headers.map((header) => util.format('%s: %s\r\n', header.name, header.value));
  buffer = buffer.concat(headerLines.join(''));
  buffer = buffer.concat('\r\n');

  return buffer.length;
}

function calculateResponseHeaderSize(perflogResponse) {
  let buffer = '';
  buffer = buffer.concat(util.format('%s %d %s\r\n', perflogResponse.protocol, perflogResponse.status, perflogResponse.statusText));
  Object.keys(perflogResponse.headers).forEach((key) => {
    buffer = buffer.concat(util.format('%s: %s\r\n', key, perflogResponse.headers[key]));
  });
  buffer = buffer.concat('\r\n');

  return buffer.length;
}

function parseCookies(cookieStrings) {
  return cookieStrings.filter(Boolean).map((cookieString) => {
    let cookie = Cookie.parse(cookieString);
    if (!cookie) {
      log.warn("Invalid cookie - failed to parse value: " + cookieString);

      return null;
    }

    return {
      'name': cookie.key,
      'value': cookie.value,
      'path': cookie.path || undefined, // must be undefined, not null, to exclude empty path
      'domain': cookie.domain || undefined,  // must be undefined, not null, to exclude empty domain
      'expires': cookie.expires === 'Infinity' ? undefined : moment(cookie.expires).toISOString(),
      'httpOnly': cookie.httpOnly,
      'secure': cookie.secure
    };
  });
}

function parseHeaders(headers) {
  if (!headers) {
    return [];
  }
  return Object.keys(headers).map((key) => {
    return {
      name: key,
      value: headers[key]
    }
  });
}

function getHeaderValue(headers, header) {
  if (!headers) {
    return '';
  }
  // http header names are case insensitive
  const lowerCaseHeader = header.toLowerCase();
  const headerNames = Object.keys(headers);
  return headerNames.filter((key) => key.toLowerCase() === lowerCaseHeader)
      .map((key) => headers[key]).shift() || '';
}

function parsePostParams(text) {
  var paramList = [];
  var queryString = urlParser.parse(text, true).query;
  Object.keys(queryString).forEach(function(name) {
    var value = queryString[name];
    if (!Array.isArray(value))
      value = [value];
    value.forEach(function(v) {
      paramList.push(
        {
          "name": name,
          "value": v
          //                    "fileName": "example.pdf",
          //                    "contentType": "application/pdf",
        });
    });
  });
  return paramList;
}

function isHttp1x(version) {
  return version.toLowerCase().startsWith('http/1.')
}

function firstNonNegative(values) {
  for (var i = 0; i < values.length; ++i) {
    if (values[i] >= 0)
      return values[i];
  }
  return -1;
}
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const EventEmitter = require('events').EventEmitter;
const chalk = require('chalk');
const fs = require('fs');
const debounce = require('ember-cli-lodash-subset').debounce;
const mapSeries = require('promise-map-series');
const Task = require('../../models/task');
const SilentError = require('silent-error');
const LiveReloadServer = require('./livereload-server');

class ExpressServerTask extends Task {
  constructor(options) {
    super(options);
    this.emitter = new EventEmitter();
    this.express = this.express || require('express');
    this.http = this.http || require('http');
    this.https = this.https || require('https');

    let serverRestartDelayTime = this.serverRestartDelayTime || 100;
    this.scheduleServerRestart = debounce(function () {
      this.restartHttpServer();
    }, serverRestartDelayTime);
  }

  on() {
    this.emitter.on.apply(this.emitter, arguments);
  }

  off() {
    this.emitter.off.apply(this.emitter, arguments);
  }

  emit() {
    this.emitter.emit.apply(this.emitter, arguments);
  }

  displayHost(specifiedHost) {
    return specifiedHost || 'localhost';
  }

  setupHttpServer() {
    if (this.startOptions.ssl) {
      this.httpServer = this.createHttpsServer();
    } else {
      this.httpServer = this.http.createServer(this.app);
    }

    // We have to keep track of sockets so that we can close them
    // when we need to restart.
    this.sockets = {};
    this.nextSocketId = 0;
    this.httpServer.on('connection', (socket) => {
      let socketId = this.nextSocketId++;
      this.sockets[socketId] = socket;

      socket.on('close', () => {
        delete this.sockets[socketId];
      });
    });
  }

  createHttpsServer() {
    if (!fs.existsSync(this.startOptions.sslKey)) {
      throw new TypeError(
        `SSL key couldn't be found in "${this.startOptions.sslKey}", ` +
          `please provide a path to an existing ssl key file with --ssl-key`
      );
    }

    if (!fs.existsSync(this.startOptions.sslCert)) {
      throw new TypeError(
        `SSL certificate couldn't be found in "${this.startOptions.sslCert}", ` +
          `please provide a path to an existing ssl certificate file with --ssl-cert`
      );
    }

    let options = {
      key: fs.readFileSync(this.startOptions.sslKey),
      cert: fs.readFileSync(this.startOptions.sslCert),
    };

    return this.https.createServer(options, this.app);
  }

  listen(port, host) {
    let server = this.httpServer;

    return new Promise((resolve, reject) => {
      server.listen(port, host);
      server.on('listening', () => {
        resolve();
        this.emit('listening');
      });
      server.on('error', reject);
    });
  }

  processAddonMiddlewares(options) {
    this.project.initializeAddons();

    return mapSeries(
      this.project.addons,
      function (addon) {
        if (addon.serverMiddleware) {
          return addon.serverMiddleware({
            app: this.app,
            options,
          });
        }
      },
      this
    );
  }

  processAppMiddlewares(options) {
    if (this.project.has(this.serverRoot)) {
      let server = this.project.require(this.serverRoot);

      if (typeof server !== 'function') {
        throw new TypeError('ember-cli expected ./server/index.js to be the entry for your mock or proxy server');
      }

      if (server.length === 3) {
        // express app is function of form req, res, next
        return this.app.use(server);
      }

      return server(this.app, options);
    }
  }

  start(options) {
    options.project = this.project;
    options.watcher = this.watcher;
    options.serverWatcher = this.serverWatcher;
    options.analytics = this.analytics;
    options.ui = this.ui;

    this.startOptions = options;

    if (this.serverWatcher) {
      this.serverWatcher.on('change', this.serverWatcherDidChange.bind(this));
      this.serverWatcher.on('add', this.serverWatcherDidChange.bind(this));
      this.serverWatcher.on('delete', this.serverWatcherDidChange.bind(this));
    }

    return this.startHttpServer();
  }

  serverWatcherDidChange() {
    this.scheduleServerRestart();
  }

  restartHttpServer() {
    if (!this.serverRestartPromise) {
      this.serverRestartPromise = this.stopHttpServer()
        .then(() => {
          this.invalidateCache(this.serverRoot);
          return this.startHttpServer();
        })
        .then(() => {
          this.emit('restart');
          this.ui.writeLine('');
          this.ui.writeLine(chalk.green('Server restarted.'));
          this.ui.writeLine('');
        })
        .catch((err) => {
          this.ui.writeError(err);
        })
        .finally(() => {
          this.serverRestartPromise = null;
        });

      return this.serverRestartPromise;
    } else {
      return this.serverRestartPromise.then(() => this.restartHttpServer());
    }
  }

  stopHttpServer() {
    return new Promise((resolve, reject) => {
      if (!this.httpServer) {
        return resolve();
      }
      this.httpServer.close((err) => {
        if (err) {
          reject(err);
          return;
        }
        this.httpServer = null;
        resolve();
      });

      // We have to force close all sockets in order to get a fast restart
      let sockets = this.sockets;
      for (let socketId in sockets) {
        sockets[socketId].destroy();
      }
    });
  }

  startHttpServer() {
    this.app = this.express();
    const compression = require('compression');
    this.app.use(
      compression({
        filter(req, res) {
          let type = res.getHeader('Content-Type');

          if (res.getHeader('x-no-compression')) {
            // don't compress responses with this response header
            return false;
          } else if (type && type.indexOf('text/event-stream') > -1) {
            // don't attempt to compress server sent events
            return false;
          } else {
            return compression.filter(req, res);
          }
        },
      })
    );

    this.setupHttpServer();

    let options = this.startOptions;
    options.httpServer = this.httpServer;
    let liveReloadServer;

    if (options.path) {
      liveReloadServer = {
        setupMiddleware() {},
      };
    } else {
      liveReloadServer = new LiveReloadServer({
        app: this.app,
        ui: options.ui,
        watcher: options.watcher,
        analytics: options.analytics,
        project: options.project,
        httpServer: options.httpServer,
      });
    }

    const config = this.project.config(options.environment);
    const middlewareOptions = Object.assign({}, options, {
      rootURL: config.rootURL,
      baseURL: config.baseURL || '/',
    });

    return Promise.resolve()
      .then(() => liveReloadServer.setupMiddleware(this.startOptions))
      .then(() => this.processAppMiddlewares(middlewareOptions))
      .then(() => this.processAddonMiddlewares(middlewareOptions))
      .then(() =>
        this.listen(options.port, options.host).catch(() => {
          throw new SilentError(
            `Could not serve on http://${this.displayHost(options.host)}:${options.port}. ` +
              `It is either in use or you do not have permission.`
          );
        })
      );
  }

  invalidateCache(serverRoot) {
    let absoluteServerRoot = path.resolve(serverRoot);
    if (absoluteServerRoot[absoluteServerRoot.length - 1] !== path.sep) {
      absoluteServerRoot += path.sep;
    }

    let allKeys = Object.keys(require.cache);
    for (let i = 0; i < allKeys.length; i++) {
      if (allKeys[i].indexOf(absoluteServerRoot) === 0) {
        delete require.cache[allKeys[i]];
      }
    }
  }
}

module.exports = ExpressServerTask;
<commit_msg>Convert express-server task to async await<commit_after>'use strict';

const path = require('path');
const EventEmitter = require('events').EventEmitter;
const chalk = require('chalk');
const fs = require('fs');
const debounce = require('ember-cli-lodash-subset').debounce;
const mapSeries = require('promise-map-series');
const Task = require('../../models/task');
const SilentError = require('silent-error');
const LiveReloadServer = require('./livereload-server');

class ExpressServerTask extends Task {
  constructor(options) {
    super(options);
    this.emitter = new EventEmitter();
    this.express = this.express || require('express');
    this.http = this.http || require('http');
    this.https = this.https || require('https');

    let serverRestartDelayTime = this.serverRestartDelayTime || 100;
    this.scheduleServerRestart = debounce(function () {
      this.restartHttpServer();
    }, serverRestartDelayTime);
  }

  on() {
    this.emitter.on.apply(this.emitter, arguments);
  }

  off() {
    this.emitter.off.apply(this.emitter, arguments);
  }

  emit() {
    this.emitter.emit.apply(this.emitter, arguments);
  }

  displayHost(specifiedHost) {
    return specifiedHost || 'localhost';
  }

  setupHttpServer() {
    if (this.startOptions.ssl) {
      this.httpServer = this.createHttpsServer();
    } else {
      this.httpServer = this.http.createServer(this.app);
    }

    // We have to keep track of sockets so that we can close them
    // when we need to restart.
    this.sockets = {};
    this.nextSocketId = 0;
    this.httpServer.on('connection', (socket) => {
      let socketId = this.nextSocketId++;
      this.sockets[socketId] = socket;

      socket.on('close', () => {
        delete this.sockets[socketId];
      });
    });
  }

  createHttpsServer() {
    if (!fs.existsSync(this.startOptions.sslKey)) {
      throw new TypeError(
        `SSL key couldn't be found in "${this.startOptions.sslKey}", ` +
          `please provide a path to an existing ssl key file with --ssl-key`
      );
    }

    if (!fs.existsSync(this.startOptions.sslCert)) {
      throw new TypeError(
        `SSL certificate couldn't be found in "${this.startOptions.sslCert}", ` +
          `please provide a path to an existing ssl certificate file with --ssl-cert`
      );
    }

    let options = {
      key: fs.readFileSync(this.startOptions.sslKey),
      cert: fs.readFileSync(this.startOptions.sslCert),
    };

    return this.https.createServer(options, this.app);
  }

  listen(port, host) {
    let server = this.httpServer;

    return new Promise((resolve, reject) => {
      server.listen(port, host);
      server.on('listening', () => {
        resolve();
        this.emit('listening');
      });
      server.on('error', reject);
    });
  }

  processAddonMiddlewares(options) {
    this.project.initializeAddons();

    return mapSeries(
      this.project.addons,
      function (addon) {
        if (addon.serverMiddleware) {
          return addon.serverMiddleware({
            app: this.app,
            options,
          });
        }
      },
      this
    );
  }

  processAppMiddlewares(options) {
    if (this.project.has(this.serverRoot)) {
      let server = this.project.require(this.serverRoot);

      if (typeof server !== 'function') {
        throw new TypeError('ember-cli expected ./server/index.js to be the entry for your mock or proxy server');
      }

      if (server.length === 3) {
        // express app is function of form req, res, next
        return this.app.use(server);
      }

      return server(this.app, options);
    }
  }

  start(options) {
    options.project = this.project;
    options.watcher = this.watcher;
    options.serverWatcher = this.serverWatcher;
    options.analytics = this.analytics;
    options.ui = this.ui;

    this.startOptions = options;

    if (this.serverWatcher) {
      this.serverWatcher.on('change', this.serverWatcherDidChange.bind(this));
      this.serverWatcher.on('add', this.serverWatcherDidChange.bind(this));
      this.serverWatcher.on('delete', this.serverWatcherDidChange.bind(this));
    }

    return this.startHttpServer();
  }

  serverWatcherDidChange() {
    this.scheduleServerRestart();
  }

  restartHttpServer() {
    if (this.serverRestartPromise) {
      return this.serverRestartPromise.then(() => this.restartHttpServer());
    }

    this.serverRestartPromise = (async () => {
      try {
        await this.stopHttpServer();
        this.invalidateCache(this.serverRoot);
        await this.startHttpServer();

        this.emit('restart');
        this.ui.writeLine('');
        this.ui.writeLine(chalk.green('Server restarted.'));
        this.ui.writeLine('');
      } catch (err) {
        this.ui.writeError(err);
      } finally {
        this.serverRestartPromise = null;
      }
    })();

    return this.serverRestartPromise;
  }

  stopHttpServer() {
    return new Promise((resolve, reject) => {
      if (!this.httpServer) {
        return resolve();
      }
      this.httpServer.close((err) => {
        if (err) {
          reject(err);
          return;
        }
        this.httpServer = null;
        resolve();
      });

      // We have to force close all sockets in order to get a fast restart
      let sockets = this.sockets;
      for (let socketId in sockets) {
        sockets[socketId].destroy();
      }
    });
  }

  startHttpServer() {
    this.app = this.express();
    const compression = require('compression');
    this.app.use(
      compression({
        filter(req, res) {
          let type = res.getHeader('Content-Type');

          if (res.getHeader('x-no-compression')) {
            // don't compress responses with this response header
            return false;
          } else if (type && type.indexOf('text/event-stream') > -1) {
            // don't attempt to compress server sent events
            return false;
          } else {
            return compression.filter(req, res);
          }
        },
      })
    );

    this.setupHttpServer();

    let options = this.startOptions;
    options.httpServer = this.httpServer;
    let liveReloadServer;

    if (options.path) {
      liveReloadServer = {
        setupMiddleware() {},
      };
    } else {
      liveReloadServer = new LiveReloadServer({
        app: this.app,
        ui: options.ui,
        watcher: options.watcher,
        analytics: options.analytics,
        project: options.project,
        httpServer: options.httpServer,
      });
    }

    const config = this.project.config(options.environment);
    const middlewareOptions = Object.assign({}, options, {
      rootURL: config.rootURL,
      baseURL: config.baseURL || '/',
    });

    return Promise.resolve()
      .then(() => liveReloadServer.setupMiddleware(this.startOptions))
      .then(() => this.processAppMiddlewares(middlewareOptions))
      .then(() => this.processAddonMiddlewares(middlewareOptions))
      .then(() =>
        this.listen(options.port, options.host).catch(() => {
          throw new SilentError(
            `Could not serve on http://${this.displayHost(options.host)}:${options.port}. ` +
              `It is either in use or you do not have permission.`
          );
        })
      );
  }

  invalidateCache(serverRoot) {
    let absoluteServerRoot = path.resolve(serverRoot);
    if (absoluteServerRoot[absoluteServerRoot.length - 1] !== path.sep) {
      absoluteServerRoot += path.sep;
    }

    let allKeys = Object.keys(require.cache);
    for (let i = 0; i < allKeys.length; i++) {
      if (allKeys[i].indexOf(absoluteServerRoot) === 0) {
        delete require.cache[allKeys[i]];
      }
    }
  }
}

module.exports = ExpressServerTask;
<|endoftext|>


<commit_before>var _ = require('lodash');
var path = require ('path');

var configCache = null;

/**
 * Load project theme configs
 *
 * @param  {String} projectPath
 * @return {object}    project plugin configs
 */
module.exports = function loadThemeConfig(projectPath) {
  if (! _.isEmpty(configCache) ) return configCache;
  if (!projectPath) projectPath = process.cwd();
  var config = {};

  var p =  path.resolve( projectPath, 'config', 'themes.js' );

  // try to load database configs from project database config
  try {
    config = require( p ).themes;
  } catch(e) {
    if (e.code != 'MODULE_NOT_FOUND' ) {
      console.error('Unknow error on load theme configs:', e);
    }
    // project plugin config file not found
    throw new Error('Theme config not found in :', p);
  }

  configCache = config;

  return config;
}<commit_msg>fix themeEngine config with a default config<commit_after>var _ = require('lodash');
var path = require ('path');

var configCache = null;

/**
 * Load project theme configs
 *
 * @param  {String} projectPath
 * @return {object}    project plugin configs
 */
module.exports = function loadThemeConfig(projectPath) {
  if (! _.isEmpty(configCache) ) return configCache;
  if (!projectPath) projectPath = process.cwd();

  var config = {
    app: 'we-theme-site-wejs',
    admin: 'we-theme-admin-default'
  };

  var p =  path.resolve( projectPath, 'config', 'themes.js' );

  // try to load database configs from project database config
  try {
    config = require( p ).themes;
  } catch(e) {
    if (e.code != 'MODULE_NOT_FOUND' ) {
      console.error('Unknow error on load theme configs:', e);
    }
  }

  configCache = config;

  return config;
}<|endoftext|>


<commit_before>var JapanAccOpeningUI = function () {
  "use strict";

    var elementObj;

  function checkValidity() {
    window.accountErrorCounter = 0;
    var letters = Content.localize().textLetters,
        numbers = Content.localize().textNumbers,
        space = Content.localize().textSpace,
        hyphen = Content.localize().textHyphen,
        period = Content.localize().textPeriod,
        apost = Content.localize().textApost;

    elementObj = {
        gender: document.getElementById('gender'),
        fname: document.getElementById('fname'),
        lname: document.getElementById('lname'),
        dobdd: document.getElementById('dobdd'),
        dobmm: document.getElementById('dobmm'),
        dobyy: document.getElementById('dobyy'),
        occupation: document.getElementById('occupation'),
        address1: document.getElementById('address1'),
        address2: document.getElementById('address2'),
        town: document.getElementById('address-town'),
        state: document.getElementById('address-state'),
        postcode: document.getElementById('address-postcode'),
        tel: document.getElementById('tel'),
        question: document.getElementById('secret-question'),
        answer: document.getElementById('secret-answer'),
        fatca: document.getElementById('fatca'),
        income: document.getElementById('annual-income'),
        asset: document.getElementById('financial-asset'),
        limit: document.getElementById('daily-loss-limit'),
        equities: document.getElementById('equities'),
        commodities: document.getElementById('commodities'),
        deposit: document.getElementById('foreign-currency-deposit'),
        margin: document.getElementById('margin-fx'),
        trust: document.getElementById('investment-trust'),
        bond: document.getElementById('public-and-corporation-bond'),
        otc: document.getElementById('otc-derivative-trading'),
        purpose: document.getElementById('trading-purpose'),
        hedge: document.getElementById('hedge-asset'),
        amount: document.getElementById('hedge-asset-amount'),
        electronic: document.getElementById('use-electronic-doc'),
        policies: document.getElementById('warnings-and-policies'),
        judgement: document.getElementById('own-judgment'),
        mechanism: document.getElementById('trading-mechanism'),
        time: document.getElementById('judgment-time'),
        total: document.getElementById('total-loss'),
        sellback: document.getElementById('sellback-loss'),
        shortsell: document.getElementById('shortsell-loss'),
        profit: document.getElementById('company-profit'),
        knowledge: document.getElementById('expert-knowledge')
    };

    var errorObj = {
        gender: document.getElementById('error-gender'),
        fname: document.getElementById('error-fname'),
        lname: document.getElementById('error-lname'),
        dobdd: document.getElementById('error-birthdate'),
        dobmm: document.getElementById('error-birthdate'),
        dobyy: document.getElementById('error-birthdate'),
        occupation: document.getElementById('error-occupation'),
        address1: document.getElementById('error-address1'),
        address2: document.getElementById('error-address2'),
        town: document.getElementById('error-town'),
        state: document.getElementById('error-state'),
        postcode: document.getElementById('error-postcode'),
        tel: document.getElementById('error-tel'),
        question: document.getElementById('error-question'),
        answer: document.getElementById('error-answer'),
        fatca: document.getElementById('error-fatca'),
        income: document.getElementById('error-annual-income'),
        asset: document.getElementById('error-financial-asset'),
        limit: document.getElementById('error-daily-loss-limit'),
        equities: document.getElementById('error-equities'),
        commodities: document.getElementById('error-commodities'),
        deposit: document.getElementById('error-foreign-currency-deposit'),
        margin: document.getElementById('error-margin-fx'),
        trust: document.getElementById('error-investment-trust'),
        bond: document.getElementById('error-public-and-corporation-bond'),
        otc: document.getElementById('error-otc-derivative-trading'),
        purpose: document.getElementById('error-trading-purpose'),
        hedge: document.getElementById('error-hedge-asset'),
        amount: document.getElementById('error-hedge-asset-amount'),
        electronic: document.getElementById('error-use-electronic-doc'),
        policies: document.getElementById('error-warnings-and-policies'),
        judgement: document.getElementById('error-own-judgment'),
        mechanism: document.getElementById('error-trading-mechanism'),
        time: document.getElementById('error-judgment-time'),
        total: document.getElementById('error-total-loss'),
        sellback: document.getElementById('error-sellback-loss'),
        shortsell: document.getElementById('error-shortsell-loss'),
        profit: document.getElementById('error-company-profit'),
        knowledge: document.getElementById('error-expert-knowledge')
    };
    var key;
    for (key in errorObj) {
      if (errorObj[key].offsetParent !== null) {
        errorObj[key].setAttribute('style', 'display:none');
      }
    }

    if (/[`~!@#$%^&*)(_=+\[}{\]\\\/";:\?><,|\d]+/.test(Trim(elementObj['fname'].value))) {
      errorObj['fname'].innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost]);
      Validate.displayErrorMessage(errorObj['fname']);
      window.accountErrorCounter++;
    }

    if (/[`~!@#$%^&*)(_=+\[}{\]\\\/";:\?><,|\d]+/.test(Trim(elementObj['lname'].value))) {
      errorObj['lname'].innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost]);
      Validate.displayErrorMessage(errorObj['lname']);
      window.accountErrorCounter++;
    }

    ValidAccountOpening.checkDate(elementObj['dobdd'], elementObj['dobmm'], elementObj['dobyy'], errorObj['dobdd']);

    if (!/^\d{3}-\d{4}$/.test(elementObj['postcode'].value)) {
      errorObj['postcode'].innerHTML = text.localize('Please follow the pattern 3 numbers, a dash, followed by 4 numbers.');
      Validate.displayErrorMessage(errorObj['postcode']);
      window.accountErrorCounter++;
    }

    if (elementObj['tel'].value.replace(/\+| /g,'').length < 6) {
      errorObj['tel'].innerHTML = Content.errorMessage('min', 6);
      Validate.displayErrorMessage(errorObj['tel']);
      window.accountErrorCounter++;
    } else if (!/^\+?[0-9\s-]{6,35}$/.test(elementObj['tel'].value)){
      errorObj['tel'].innerHTML = Content.errorMessage('reg', [numbers, space, hyphen]);
      Validate.displayErrorMessage(errorObj['tel']);
      window.accountErrorCounter++;
    }

    if (!/^\d+$/.test(elementObj['limit'].value)) {
      errorObj['limit'].innerHTML = Content.errorMessage('reg', [numbers]);
      Validate.displayErrorMessage(errorObj['limit']);
      window.accountErrorCounter++;
    }

    if (elementObj['amount'].offsetParent !== null && !/^\d+$/.test(elementObj['amount'].value)) {
      errorObj['amount'].innerHTML = Content.errorMessage('reg', [numbers]);
      Validate.displayErrorMessage(errorObj['amount']);
      window.accountErrorCounter++;
    }

    if (elementObj['answer'].value.length < 2 ) {
      errorObj['answer'].innerHTML = Content.errorMessage('min', 2);
      Validate.displayErrorMessage(errorObj['answer']);
      window.accountErrorCounter++;
    }

    for (key in elementObj) {
      if (elementObj[key].offsetParent !== null && key !== 'address2') {
        if (/^$/.test(Trim(elementObj[key].value)) && elementObj[key].type !== 'checkbox') {
          errorObj[key].innerHTML = Content.errorMessage('req');
          Validate.displayErrorMessage(errorObj[key]);
          window.accountErrorCounter++;
        }
        if (elementObj[key].type === 'checkbox' && !elementObj[key].checked) {
          errorObj[key].innerHTML = Content.errorMessage('req');
          Validate.displayErrorMessage(errorObj[key]);
          window.accountErrorCounter++;
        }
      }
    }

    if (window.accountErrorCounter === 0) {
      for (key in errorObj) {
        if (errorObj[key].offsetParent !== null) {
          errorObj[key].setAttribute('style', 'display:none');
        }
      }
      return 1;
    }
    return 0;
  }

    function fireRequest() {
        JapanAccOpeningData.getJapanAcc(elementObj);
    }

  return {
    checkValidity: checkValidity,
      fireRequest: fireRequest,
  };
}();
<commit_msg>revert back to 1<commit_after>var JapanAccOpeningUI = function () {
  "use strict";

    var elementObj;

  function checkValidity() {
    window.accountErrorCounter = 0;
    var letters = Content.localize().textLetters,
        numbers = Content.localize().textNumbers,
        space = Content.localize().textSpace,
        hyphen = Content.localize().textHyphen,
        period = Content.localize().textPeriod,
        apost = Content.localize().textApost;

    elementObj = {
        gender: document.getElementById('gender'),
        fname: document.getElementById('fname'),
        lname: document.getElementById('lname'),
        dobdd: document.getElementById('dobdd'),
        dobmm: document.getElementById('dobmm'),
        dobyy: document.getElementById('dobyy'),
        occupation: document.getElementById('occupation'),
        address1: document.getElementById('address1'),
        address2: document.getElementById('address2'),
        town: document.getElementById('address-town'),
        state: document.getElementById('address-state'),
        postcode: document.getElementById('address-postcode'),
        tel: document.getElementById('tel'),
        question: document.getElementById('secret-question'),
        answer: document.getElementById('secret-answer'),
        fatca: document.getElementById('fatca'),
        income: document.getElementById('annual-income'),
        asset: document.getElementById('financial-asset'),
        limit: document.getElementById('daily-loss-limit'),
        equities: document.getElementById('equities'),
        commodities: document.getElementById('commodities'),
        deposit: document.getElementById('foreign-currency-deposit'),
        margin: document.getElementById('margin-fx'),
        trust: document.getElementById('investment-trust'),
        bond: document.getElementById('public-and-corporation-bond'),
        otc: document.getElementById('otc-derivative-trading'),
        purpose: document.getElementById('trading-purpose'),
        hedge: document.getElementById('hedge-asset'),
        amount: document.getElementById('hedge-asset-amount'),
        electronic: document.getElementById('use-electronic-doc'),
        policies: document.getElementById('warnings-and-policies'),
        judgement: document.getElementById('own-judgment'),
        mechanism: document.getElementById('trading-mechanism'),
        time: document.getElementById('judgment-time'),
        total: document.getElementById('total-loss'),
        sellback: document.getElementById('sellback-loss'),
        shortsell: document.getElementById('shortsell-loss'),
        profit: document.getElementById('company-profit'),
        knowledge: document.getElementById('expert-knowledge')
    };

    var errorObj = {
        gender: document.getElementById('error-gender'),
        fname: document.getElementById('error-fname'),
        lname: document.getElementById('error-lname'),
        dobdd: document.getElementById('error-birthdate'),
        dobmm: document.getElementById('error-birthdate'),
        dobyy: document.getElementById('error-birthdate'),
        occupation: document.getElementById('error-occupation'),
        address1: document.getElementById('error-address1'),
        address2: document.getElementById('error-address2'),
        town: document.getElementById('error-town'),
        state: document.getElementById('error-state'),
        postcode: document.getElementById('error-postcode'),
        tel: document.getElementById('error-tel'),
        question: document.getElementById('error-question'),
        answer: document.getElementById('error-answer'),
        fatca: document.getElementById('error-fatca'),
        income: document.getElementById('error-annual-income'),
        asset: document.getElementById('error-financial-asset'),
        limit: document.getElementById('error-daily-loss-limit'),
        equities: document.getElementById('error-equities'),
        commodities: document.getElementById('error-commodities'),
        deposit: document.getElementById('error-foreign-currency-deposit'),
        margin: document.getElementById('error-margin-fx'),
        trust: document.getElementById('error-investment-trust'),
        bond: document.getElementById('error-public-and-corporation-bond'),
        otc: document.getElementById('error-otc-derivative-trading'),
        purpose: document.getElementById('error-trading-purpose'),
        hedge: document.getElementById('error-hedge-asset'),
        amount: document.getElementById('error-hedge-asset-amount'),
        electronic: document.getElementById('error-use-electronic-doc'),
        policies: document.getElementById('error-warnings-and-policies'),
        judgement: document.getElementById('error-own-judgment'),
        mechanism: document.getElementById('error-trading-mechanism'),
        time: document.getElementById('error-judgment-time'),
        total: document.getElementById('error-total-loss'),
        sellback: document.getElementById('error-sellback-loss'),
        shortsell: document.getElementById('error-shortsell-loss'),
        profit: document.getElementById('error-company-profit'),
        knowledge: document.getElementById('error-expert-knowledge')
    };
    var key;
    for (key in errorObj) {
      if (errorObj[key].offsetParent !== null) {
        errorObj[key].setAttribute('style', 'display:none');
      }
    }

    if (/[`~!@#$%^&*)(_=+\[}{\]\\\/";:\?><,|\d]+/.test(Trim(elementObj['fname'].value))) {
      errorObj['fname'].innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost]);
      Validate.displayErrorMessage(errorObj['fname']);
      window.accountErrorCounter++;
    }

    if (/[`~!@#$%^&*)(_=+\[}{\]\\\/";:\?><,|\d]+/.test(Trim(elementObj['lname'].value))) {
      errorObj['lname'].innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost]);
      Validate.displayErrorMessage(errorObj['lname']);
      window.accountErrorCounter++;
    }

    ValidAccountOpening.checkDate(elementObj['dobdd'], elementObj['dobmm'], elementObj['dobyy'], errorObj['dobdd']);

    if (!/^\d{3}-\d{4}$/.test(elementObj['postcode'].value)) {
      errorObj['postcode'].innerHTML = text.localize('Please follow the pattern 3 numbers, a dash, followed by 4 numbers.');
      Validate.displayErrorMessage(errorObj['postcode']);
      window.accountErrorCounter++;
    }

    if (elementObj['tel'].value.replace(/\+| /g,'').length < 6) {
      errorObj['tel'].innerHTML = Content.errorMessage('min', 6);
      Validate.displayErrorMessage(errorObj['tel']);
      window.accountErrorCounter++;
    } else if (!/^\+?[0-9\s-]{6,35}$/.test(elementObj['tel'].value)){
      errorObj['tel'].innerHTML = Content.errorMessage('reg', [numbers, space, hyphen]);
      Validate.displayErrorMessage(errorObj['tel']);
      window.accountErrorCounter++;
    }

    if (!/^\d+$/.test(elementObj['limit'].value)) {
      errorObj['limit'].innerHTML = Content.errorMessage('reg', [numbers]);
      Validate.displayErrorMessage(errorObj['limit']);
      window.accountErrorCounter++;
    }

    if (elementObj['amount'].offsetParent !== null && !/^\d+$/.test(elementObj['amount'].value)) {
      errorObj['amount'].innerHTML = Content.errorMessage('reg', [numbers]);
      Validate.displayErrorMessage(errorObj['amount']);
      window.accountErrorCounter++;
    }

    for (key in elementObj) {
      if (elementObj[key].offsetParent !== null && key !== 'address2') {
        if (/^$/.test(Trim(elementObj[key].value)) && elementObj[key].type !== 'checkbox') {
          errorObj[key].innerHTML = Content.errorMessage('req');
          Validate.displayErrorMessage(errorObj[key]);
          window.accountErrorCounter++;
        }
        if (elementObj[key].type === 'checkbox' && !elementObj[key].checked) {
          errorObj[key].innerHTML = Content.errorMessage('req');
          Validate.displayErrorMessage(errorObj[key]);
          window.accountErrorCounter++;
        }
      }
    }

    if (window.accountErrorCounter === 0) {
      for (key in errorObj) {
        if (errorObj[key].offsetParent !== null) {
          errorObj[key].setAttribute('style', 'display:none');
        }
      }
      return 1;
    }
    return 0;
  }

    function fireRequest() {
        JapanAccOpeningData.getJapanAcc(elementObj);
    }

  return {
    checkValidity: checkValidity,
      fireRequest: fireRequest,
  };
}();
<|endoftext|>


<commit_before>const BinarySocket = require('../../socket');
const BinaryPjax   = require('../../../base/binary_pjax');
const Client       = require('../../../base/client');
const urlFor       = require('../../../base/url').urlFor;

const AccountType = (() => {
    let url_real,
        url_ico,
        container;
    const onLoad = () => {
        BinarySocket.wait('landing_company').then((response_lc) => {
            url_ico  = `${urlFor('new_account/realws')  }#ico`;
            url_real = urlFor(Client.getUpgradeInfo(response_lc).upgrade_link);
            container = document.getElementById('account_type_container');

            if(Client.canOpenICO() && container) {
                container.setVisibility(1);
                addEventListener();
            } else {
                BinaryPjax.load(url_real);
            }
        });

        const addEventListener = () => {
            $(container)
                .find('#btn_submit')
                .off('click')
                .on('click', () => {
                    const value = $(container).find('input[type=radio]:checked').val();
                    if (value === 'ico') {
                        BinaryPjax.load(url_ico);
                    } else {
                        BinaryPjax.load(url_real);
                    }
                });
        };
    };

    return {
        onLoad,
    };
})();

module.exports = AccountType;
<commit_msg>Rename function<commit_after>const BinarySocket = require('../../socket');
const BinaryPjax   = require('../../../base/binary_pjax');
const Client       = require('../../../base/client');
const urlFor       = require('../../../base/url').urlFor;

const AccountType = (() => {
    let url_real,
        url_ico,
        container;
    const onLoad = () => {
        BinarySocket.wait('landing_company').then((response_lc) => {
            url_ico  = `${urlFor('new_account/realws')  }#ico`;
            url_real = urlFor(Client.getUpgradeInfo(response_lc).upgrade_link);
            container = document.getElementById('account_type_container');

            if(Client.canOpenICO() && container) {
                container.setVisibility(1);
                onSubmit();
            } else {
                BinaryPjax.load(url_real);
            }
        });

        const onSubmit = () => {
            $(container)
                .find('#btn_submit')
                .off('click')
                .on('click', () => {
                    const value = $(container).find('input[type=radio]:checked').val();
                    if (value === 'ico') {
                        BinaryPjax.load(url_ico);
                    } else {
                        BinaryPjax.load(url_real);
                    }
                });
        };
    };

    return {
        onLoad,
    };
})();

module.exports = AccountType;
<|endoftext|>


<commit_before>// var App = {
//     Views: {},
//     Controllers: {},
//     init: function() {
//         new App.Controllers.Tasks();
//         Backbone.history.start();
//     }
// };

//jQuery when DOM loads run this
$(function(){

  //Backbone Model

  window.Task = Backbone.Model.extend({
    url: function() {
      return this.id ? '/tasks/' + this.id : '/tasks'; //Ternary, look it up if you aren't sure
    },

    defaults: { task: {
      title: "Please enter a title",
			task_list_id: "",
			user_id: "",
			created_by: "",
			priority: false,
			completed: false,
			type: "",
			due_date: "",
      description: ""
    }},

    initialize: function(){
      //Can be used to initialize Model attributes
    }
  });

  //Collection

  window.TaskCollection = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
  });

  window.Tasks = new TaskCollection;

	//View

  window.TaskView = Backbone.View.extend({
    // tagName: "tr",
		tagName: "div",
		className: "task_holder",

    events: {
      //Can be used for handling events on the template
    },

    initialize: function(){
      //this.render();
    },

    render: function(){
      var task = this.model.toJSON();
      //Template stuff goes here
      $(this.el).html(ich.task_template(task));
      return this;
    }
  });

	window.AppView = Backbone.View.extend({

    el: $("#tasks_app"),

    events: {
      "submit form#create_task_form": "createTask",
			"click .opener": "openTask"
    },

    initialize: function(){
      _.bindAll(this, 'addOne', 'addAll');

      Tasks.bind('add', this.addOne);
      Tasks.bind('refresh', this.addAll);
      Tasks.bind('all', this.render);

      Tasks.fetch(); //This Gets the Model from the Server
    },

    addOne: function(task) {
      var view = new TaskView({model: task});
      // this.$("#task_table").append(view.render().el);
			this.$("#task_holder").append(view.render().el);
    },

    addAll: function(){
      Tasks.each(this.addOne);
    },

    newAttributes: function(event) {

      return { task: {
          task_list_id: event["task[task_list_id]"],
					user_id: event["task[user_id]"],
					created_by: event["task[created_by]"],
					priority: event["task[priority]"],
					completed: event["task[completed]"],
					type: event["type"],
					due_date: event["task[due_date]"],
					title: event["task[title]"],
          description: event["task[description]"]
        }}
    },

    createTask: function(e) {
      e.preventDefault(); //This prevents the form from submitting normally

			var values = {};
			$.each($('form#create_task_form').serializeArray(), function(i, field) {
			    values[field.name] = field.value;
			});

      var params = this.newAttributes(values);

			Tasks.create(params);

    },

		openTask: function() {
			// $(this.el)
			var opener = this.$(".slide");

		}

  });

	window.App = new AppView;

});
<commit_msg>adding slide effects<commit_after>// var App = {
//     Views: {},
//     Controllers: {},
//     init: function() {
//         new App.Controllers.Tasks();
//         Backbone.history.start();
//     }
// };

//jQuery when DOM loads run this
$(function(){

  //Backbone Model

  window.Task = Backbone.Model.extend({
    url: function() {
      return this.id ? '/tasks/' + this.id : '/tasks'; //Ternary, look it up if you aren't sure
    },

    defaults: { task: {
      title: "Please enter a title",
			task_list_id: "",
			user_id: "",
			created_by: "",
			priority: false,
			completed: false,
			type: "",
			due_date: "",
      description: ""
    }},

    initialize: function(){
      //Can be used to initialize Model attributes
    }
  });

  //Collection

  window.TaskCollection = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
  });

  window.Tasks = new TaskCollection;

	//View

  window.TaskView = Backbone.View.extend({
    // tagName: "tr",
		tagName: "div",
		className: "task_holder",

    events: {
      //Can be used for handling events on the template
    },

    initialize: function(){
      //this.render();
    },

    render: function(){
      var task = this.model.toJSON();
      //Template stuff goes here
      $(this.el).html(ich.task_template(task));
      return this;
    }
  });

	window.AppView = Backbone.View.extend({

    el: $("#tasks_app"),

    events: {
      "submit form#create_task_form": "createTask",
			"click .opener": "openTask"
    },

    initialize: function(){
      _.bindAll(this, 'addOne', 'addAll');

      Tasks.bind('add', this.addOne);
      Tasks.bind('refresh', this.addAll);
      Tasks.bind('all', this.render);

      Tasks.fetch(); //This Gets the Model from the Server
    },

    addOne: function(task) {
      var view = new TaskView({model: task});
      // this.$("#task_table").append(view.render().el);
			this.$("#task_holder").append(view.render().el);
    },

    addAll: function(){
      Tasks.each(this.addOne);
    },

    newAttributes: function(event) {

      return { task: {
          task_list_id: event["task[task_list_id]"],
					user_id: event["task[user_id]"],
					created_by: event["task[created_by]"],
					priority: event["task[priority]"],
					completed: event["task[completed]"],
					type: event["type"],
					due_date: event["task[due_date]"],
					title: event["task[title]"],
          description: event["task[description]"]
        }}
    },

    createTask: function(e) {
      e.preventDefault(); //This prevents the form from submitting normally

			var values = {};
			$.each($('form#create_task_form').serializeArray(), function(i, field) {
			    values[field.name] = field.value;
			});

      var params = this.newAttributes(values);

			Tasks.create(params);

    },

		openTask: function(targ) {
			var id = targ.currentTarget.id;
			var opener = this.$("#slide_" + id);
			var slideSpeed = 500;
			var slideHolder = $("task_row_" + id);

			if (opener.hasClass('slide-active')){
				opener.css({overflow:'hidden'});
				opener.slideUp(slideSpeed);
				opener.removeClass('slide-active');
			} else {
				opener.slideDown(slideSpeed, function(){
					opener.css({overflow:'visibile'});
				})
				opener.addClass('slide-active');
			}

			return false; // Make sure it does not redirect anywhere
		}

  });

	window.App = new AppView;

});
<|endoftext|>


<commit_before>(function(window, document, Granite, $) {
    "use strict";

    var TWITTER_ACTIVATOR = ".cq-siteadmin-admin-actions-twitter-activator";

    $(document).on("click", TWITTER_ACTIVATOR, function(e) {
        var selection = $(".foundation-collection").first().find(".foundation-selections-item").first();
        var path = selection.data("foundationCollectionItemId") || selection.data("path");

        var ui = $(window).adaptTo("foundation-ui");
        var title = Granite.I18n.get("Publish to Twitter");
        var message = Granite.I18n.get("Do you want to publish a link to this page to Twitter?");

        ui.prompt(title, message, "notice", [
            {
                text: Granite.I18n.get("Yes"),
                primary: true,
                id: "yes"
            },
            {
                text: Granite.I18n.get("No"),
                id: "no"
            }
        ], function (btnId) {
            if (btnId === "yes") {
                var notificationSlider = new Granite.UI.NotificationSlider($(".endor-Page-content.endor-Panel.foundation-content"));
                notificationSlider.notify({
                    content: Granite.I18n.get("Page is being published to Twitter"),
                    type: "info",
                    closable: true,
                    className: "notification-alert--absolute admin-notification"
                });
            }
        });
    });

})(window, document, Granite, Granite.$);
<commit_msg>Update twitter.js<commit_after>/*
 * #%L
 * aem-admin-extension-customize-sites
 * %%
 * Copyright (C) 2014 Adobe
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
 (function(window, document, Granite, $) {
    "use strict";

    var TWITTER_ACTIVATOR = ".cq-siteadmin-admin-actions-twitter-activator";

    $(document).on("click", TWITTER_ACTIVATOR, function(e) {
        var selection = $(".foundation-collection").first().find(".foundation-selections-item").first();
        var path = selection.data("foundationCollectionItemId") || selection.data("path");

        var ui = $(window).adaptTo("foundation-ui");
        var title = Granite.I18n.get("Publish to Twitter");
        var message = Granite.I18n.get("Do you want to publish a link to this page to Twitter?");

        ui.prompt(title, message, "notice", [
            {
                text: Granite.I18n.get("Yes"),
                primary: true,
                id: "yes"
            },
            {
                text: Granite.I18n.get("No"),
                id: "no"
            }
        ], function (btnId) {
            if (btnId === "yes") {
                var notificationSlider = new Granite.UI.NotificationSlider($(".endor-Page-content.endor-Panel.foundation-content"));
                notificationSlider.notify({
                    content: Granite.I18n.get("Page is being published to Twitter"),
                    type: "info",
                    closable: true,
                    className: "notification-alert--absolute admin-notification"
                });
            }
        });
    });

})(window, document, Granite, Granite.$);
<|endoftext|>