<commit_before>import IdentityManager from 'service-framework/dist/IdentityManager';
import {Syncher} from 'service-framework/dist/Syncher';
import Discovery from 'service-framework/dist/Discovery';
import {divideURL} from '../utils/utils';
import Search from '../utils/Search';
import EventEmitter from '../utils/EventEmitter';
import UserAvailabilityController from './UserAvailabilityController';

class UserAvailabilityObserver extends EventEmitter {

  constructor(hypertyURL, bus, configuration) {
    if (!hypertyURL) throw new Error('The hypertyURL is a needed parameter');
    if (!bus) throw new Error('The MiniBus is a needed parameter');
    if (!configuration) throw new Error('The configuration is a needed parameter ');

    super();

    let _this = this;
    //let identityManager = new IdentityManager(hypertyURL, configuration.runtimeURL, bus);
    console.log('[UserAvailabilityObserver] started with hypertyURL->', hypertyURL);
    _this._domain = divideURL(hypertyURL).domain;
    _this._objectDescURL = 'hyperty-catalogue://catalogue.' + _this._domain + '/.well-known/dataschema/Context';

    _this._users2observe = [];

    _this._syncher = new Syncher(hypertyURL, bus, configuration);
    let discovery = new Discovery(hypertyURL, configuration.runtimeURL, bus);
    _this._discovery = discovery;
    //_this.identityManager = identityManager;
    //_this.search = new Search(discovery, identityManager);
    window.discovery = _this._discovery;
  }

  start () {
    let _this = this;

    return new Promise((resolve, reject) => {
      _this._syncher.resumeObservers({store: true}).then((observers) => {

        let observersList = Object.keys(observers);

        if (observersList.length  > 0) {

        console.log('[UserAvailabilityObserver.start] resuming: ', observers);

        /*observersList.forEach((i)=>{
          _this._users2observe.push(new UserAvailabilityController(observers[i]));
        });*/

        resolve(observers);
      } else {
        resolve(false);
      }

      }).catch((reason) => {
        console.info('[UserAvailabilityObserver] Resume Observer failed | ', reason);
        resolve(false);
      });
    }).catch((reason) => {
    reject('[UserAvailabilityObserver] Start failed | ', reason);
  });
}

  onResumeObserver(callback) {
     let _this = this;
     _this._onResumeObserver = callback;
   }

  discoverUsers(email,domain)
  {
    let _this = this;
    return new Promise(function(resolve,reject) {
      //TODO: replace by _discovery.discoverHypertiesDO(..) when DR notification works
      _this._discovery.discoverHyperties(email, ['context'], ['availability_context'], domain).then(hyperties =>{
      //_this.search.users([email], [domain], ['context'], ['availability_context']).then(function(a) {
        console.log('[UserAvailabilityObserver.discoverUsers] discovery result->', hyperties);
        let discovered = [];
        let disconnected = [];
        hyperties.forEach(hyperty =>{
          if (hyperty.status === 'live') {
            discovered.push(hyperty);
          } else {
            disconnected.push(hyperty);
            };
        });

        if (discovered.length > 0) {
          console.log('[UserAvailabilityObserver.discoverUsers] returning discovered hyperties data->', discovered);
          resolve(discovered);
        } else if (disconnected.length > 0) {
          console.log('[UserAvailabilityObserver.discoverUsers] disconnected Hyperties ', disconnected);
          resolve([]);

          //TODO: uncommented below when DR notification works
          /*
          disconnected[0].onLive(()=>{
            discovered.push(disconnected[0].data);
            resolve(discovered);
          });*/
        }
      });
    });
  }

  /**
   * This function is used to start the user availability observation for a certain user availability reporter
   * @param  {DiscoveredObject} hyperty       Hyperty to be observed.
   * @return {<Promise> DataObjectObserver}      It returns as a Promise the UserAvailability Data Object Observer.
   */

  observe(hyperty)
    {
      let _this = this;
      return new Promise(function(resolve,reject) {
          _this._discovery.discoverDataObjectsPerReporter(hyperty.hypertyID, ['context'], ['availability_context'],  _this._domain).then(function(dataObjects) {
            console.log('[UserAvailabilityObserver.discoverAvailability] discovered user availability objects ', dataObjects);
          let last = 0;
          let url;

          dataObjects.forEach( (dataObject) => {
            if (dataObject.hasOwnProperty('lastModified') && dataObject.hasOwnProperty('url') && Date.parse(dataObject.lastModified) > last) {
              last = dataObject.lastModified;
              url = dataObject.url;
                //console.log('URL DATA Object', url);
          }
        });
        if (last != 0 && url) {
          resolve(_this._subscribeAvailability(hyperty.userID, url));
        } else {
          reject ('[UserAvailabilityObserver.discoverAvailability] discovered DataObjecs are invalid', dataObjects);
        }
      });
    });
  }

  _subscribeAvailability(userID, url) {
    let _this = this;
    return new Promise(function(resolve,reject) {
        _this._syncher.subscribe(_this._objectDescURL, url).then((availability) => {
          console.log('[UserAvailabilityObserver.observeAvailability] observer object', availability);

          //let newUserAvailability = new UserAvailabilityController(availability, userID);

          _this._users2observe.push(availability);

          resolve(availability);
        });
      });
  }
}

/**
 * This function is used to stop the user availability observation for a certain user
 * @param  {string} availability       the UserAvailability Data Object Observer URL to be unobserved.
 */

  unobserve(availability)
    {
      let _this = this;

      _this._users2observe.forEach( (user, index) => {
        if (user.url === availability) {
          user.unsubscribe();
          _this._users2observe.splice(index, 1);
        }

      });
  }

export default function activate(hypertyURL, bus, configuration) {
  return {
    name: 'UserAvailabilityObserver',
    instance: new UserAvailabilityObserver(hypertyURL, bus, configuration)
  };
}
<commit_msg>UserAvailabilityObserver: removed controller import<commit_after>import IdentityManager from 'service-framework/dist/IdentityManager';
import {Syncher} from 'service-framework/dist/Syncher';
import Discovery from 'service-framework/dist/Discovery';
import {divideURL} from '../utils/utils';
import Search from '../utils/Search';
import EventEmitter from '../utils/EventEmitter';

class UserAvailabilityObserver extends EventEmitter {

  constructor(hypertyURL, bus, configuration) {
    if (!hypertyURL) throw new Error('The hypertyURL is a needed parameter');
    if (!bus) throw new Error('The MiniBus is a needed parameter');
    if (!configuration) throw new Error('The configuration is a needed parameter ');

    super();

    let _this = this;
    //let identityManager = new IdentityManager(hypertyURL, configuration.runtimeURL, bus);
    console.log('[UserAvailabilityObserver] started with hypertyURL->', hypertyURL);
    _this._domain = divideURL(hypertyURL).domain;
    _this._objectDescURL = 'hyperty-catalogue://catalogue.' + _this._domain + '/.well-known/dataschema/Context';

    _this._users2observe = [];

    _this._syncher = new Syncher(hypertyURL, bus, configuration);
    let discovery = new Discovery(hypertyURL, configuration.runtimeURL, bus);
    _this._discovery = discovery;
    //_this.identityManager = identityManager;
    //_this.search = new Search(discovery, identityManager);
    window.discovery = _this._discovery;
  }

  start () {
    let _this = this;

    return new Promise((resolve, reject) => {
      _this._syncher.resumeObservers({store: true}).then((observers) => {

        let observersList = Object.keys(observers);

        if (observersList.length  > 0) {

        console.log('[UserAvailabilityObserver.start] resuming: ', observers);

        /*observersList.forEach((i)=>{
          _this._users2observe.push(new UserAvailabilityController(observers[i]));
        });*/

        resolve(observers);
      } else {
        resolve(false);
      }

      }).catch((reason) => {
        console.info('[UserAvailabilityObserver] Resume Observer failed | ', reason);
        resolve(false);
      });
    }).catch((reason) => {
    reject('[UserAvailabilityObserver] Start failed | ', reason);
  });
}

  onResumeObserver(callback) {
     let _this = this;
     _this._onResumeObserver = callback;
   }

  discoverUsers(email,domain)
  {
    let _this = this;
    return new Promise(function(resolve,reject) {
      //TODO: replace by _discovery.discoverHypertiesDO(..) when DR notification works
      _this._discovery.discoverHyperties(email, ['context'], ['availability_context'], domain).then(hyperties =>{
      //_this.search.users([email], [domain], ['context'], ['availability_context']).then(function(a) {
        console.log('[UserAvailabilityObserver.discoverUsers] discovery result->', hyperties);
        let discovered = [];
        let disconnected = [];
        hyperties.forEach(hyperty =>{
          if (hyperty.status === 'live') {
            discovered.push(hyperty);
          } else {
            disconnected.push(hyperty);
            };
        });

        if (discovered.length > 0) {
          console.log('[UserAvailabilityObserver.discoverUsers] returning discovered hyperties data->', discovered);
          resolve(discovered);
        } else if (disconnected.length > 0) {
          console.log('[UserAvailabilityObserver.discoverUsers] disconnected Hyperties ', disconnected);
          resolve([]);

          //TODO: uncommented below when DR notification works
          /*
          disconnected[0].onLive(()=>{
            discovered.push(disconnected[0].data);
            resolve(discovered);
          });*/
        }
      });
    });
  }

  /**
   * This function is used to start the user availability observation for a certain user availability reporter
   * @param  {DiscoveredObject} hyperty       Hyperty to be observed.
   * @return {<Promise> DataObjectObserver}      It returns as a Promise the UserAvailability Data Object Observer.
   */

  observe(hyperty)
    {
      let _this = this;
      return new Promise(function(resolve,reject) {
          _this._discovery.discoverDataObjectsPerReporter(hyperty.hypertyID, ['context'], ['availability_context'],  _this._domain).then(function(dataObjects) {
            console.log('[UserAvailabilityObserver.discoverAvailability] discovered user availability objects ', dataObjects);
          let last = 0;
          let url;

          dataObjects.forEach( (dataObject) => {
            if (dataObject.hasOwnProperty('lastModified') && dataObject.hasOwnProperty('url') && Date.parse(dataObject.lastModified) > last) {
              last = dataObject.lastModified;
              url = dataObject.url;
                //console.log('URL DATA Object', url);
          }
        });
        if (last != 0 && url) {
          resolve(_this._subscribeAvailability(hyperty.userID, url));
        } else {
          reject ('[UserAvailabilityObserver.discoverAvailability] discovered DataObjecs are invalid', dataObjects);
        }
      });
    });
  }

  _subscribeAvailability(userID, url) {
    let _this = this;
    return new Promise(function(resolve,reject) {
        _this._syncher.subscribe(_this._objectDescURL, url).then((availability) => {
          console.log('[UserAvailabilityObserver.observeAvailability] observer object', availability);

          //let newUserAvailability = new UserAvailabilityController(availability, userID);

          _this._users2observe.push(availability);

          resolve(availability);
        });
      });
  }
}

/**
 * This function is used to stop the user availability observation for a certain user
 * @param  {string} availability       the UserAvailability Data Object Observer URL to be unobserved.
 */

  unobserve(availability)
    {
      let _this = this;

      _this._users2observe.forEach( (user, index) => {
        if (user.url === availability) {
          user.unsubscribe();
          _this._users2observe.splice(index, 1);
        }

      });
  }

export default function activate(hypertyURL, bus, configuration) {
  return {
    name: 'UserAvailabilityObserver',
    instance: new UserAvailabilityObserver(hypertyURL, bus, configuration)
  };
}
<|endoftext|>


<commit_before>/*
 *     (C) Copyright 2012 Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global StyledElements, LayoutManagerFactory, Wirecloud, gettext*/

(function () {

    "use strict";

    var MarketplaceView, onGetStoresSuccess, onGetStoresFailure;

    onGetStoresSuccess = function onGetStoresSuccess(options, view_info) {
        var info, old_views, view_element, view_constructor, first_element = null;

        this.loading = false;
        this.error = false;

        old_views = this.viewsByName;
        this.viewsByName = {};

        for (info in view_info) {

            view_element = JSON.parse(view_info[info]);
            view_element.name = info;

            if (info in old_views) {
                this.viewsByName[info] = old_views[info];
                delete old_views[info];
            } else {
                view_constructor = Wirecloud.MarketManager.getMarketViewClass(view_element.type);
                this.viewsByName[info] = this.alternatives.createAlternative({alternative_constructor: view_constructor, containerOptions: {catalogue: this, marketplace_desc: view_element}});
            }

            this.number_of_alternatives += 1;
            if (first_element === null) {
                first_element = this.viewsByName[info];
            }
        }

        for (info in old_views) {
            this.alternatives.removeAlternative(old_views[info]);
            old_views[info].destroy();
        }

        // Refresh wirecloud header as current marketplace may have been changed
        LayoutManagerFactory.getInstance().header.refresh();

        if (typeof options.onSuccess === 'function') {
            options.onSuccess();
        }
        if (typeof options.onComplete === 'function') {
            options.onComplete();
        }
    };

    onGetStoresFailure = function onGetStoresFailure(options, msg) {
        this.loading = false;
        this.error = true;

        LayoutManagerFactory.getInstance().header.refresh();
        if (typeof options.onFailure === 'function') {
            options.onSuccess();
        }
        if (typeof options.onFailure === 'function') {
            options.onComplete();
        }
    };

    MarketplaceView = function MarketplaceView(id, options) {
        options.id = 'marketplace';
        StyledElements.Alternative.call(this, id, options);

        this.viewsByName = {};
        this.alternatives = new StyledElements.StyledAlternatives();
        this.alternatives.addEventListener('postTransition', function () {
            LayoutManagerFactory.getInstance().header.refresh();
        });
        this.appendChild(this.alternatives);

        this.marketMenu = new StyledElements.PopupMenu();
        this.marketMenu.append(new Wirecloud.ui.MarketplaceViewMenuItems(this));

        this.addEventListener('show', function (view) {
            view.alternatives.getCurrentAlternative().refresh_if_needed();
        });

        this.number_of_alternatives = 0;
        this.loading = true;
        this.error = false;
        Wirecloud.MarketManager.getMarkets(onGetStoresSuccess.bind(this, {}), onGetStoresFailure.bind(this, {}));
    };

    MarketplaceView.prototype = new StyledElements.Alternative();

    MarketplaceView.prototype.view_name = 'marketplace';

    MarketplaceView.prototype.getBreadcrum = function () {
        var label, breadcrum;

        if (this.loading) {
            label = gettext('loading...');
        } else if (this.error) {
            label = gettext('list not available');
        } else if (this.number_of_alternatives > 0) {
            label = this.alternatives.getCurrentAlternative().getLabel();
        } else {
            label = gettext('no registered marketplace');
        }

        breadcrum = [
            {
                'label': 'marketplace'
            },
            {
                'label': label,
                'menu': this.marketMenu
            }
        ];

        // If no alternatives exist, it is no posible to have an extra breadcrum
        if (!this.loading && !this.error && this.number_of_alternatives > 0) {
            if (typeof this.alternatives.getCurrentAlternative().getExtraBreadcrum === 'function') {
                breadcrum = breadcrum.concat(this.alternatives.getCurrentAlternative().getExtraBreadcrum());
            }
        }
        return breadcrum;
    };

    MarketplaceView.prototype.refreshViewInfo = function refreshViewInfo(options) {

        if (this.loading) {
            return;
        }

        if (typeof options !== 'object') {
            options = {};
        }

        this.loading = true;
        LayoutManagerFactory.getInstance().header.refresh();

        this.number_of_alternatives = 0;

        Wirecloud.MarketManager.getMarkets(onGetStoresSuccess.bind(this, options), onGetStoresFailure.bind(this, options));
    };

    MarketplaceView.prototype.addMarket = function addMarket(market_info) {
        var view_constructor = Wirecloud.MarketManager.getMarketViewClass(market_info.type);
        this.viewsByName[market_info.name] = this.alternatives.createAlternative({alternative_constructor: view_constructor, containerOptions: {catalogue: this, marketplace_desc: market_info}});

        this.number_of_alternatives += 1;
        this.alternatives.showAlternative(this.viewsByName[market_info.name]);
    };

    window.MarketplaceView = MarketplaceView;
})();
<commit_msg>Make local catalogue the default one<commit_after>/*
 *     (C) Copyright 2012 Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global StyledElements, LayoutManagerFactory, Wirecloud, gettext*/

(function () {

    "use strict";

    var MarketplaceView, onGetStoresSuccess, onGetStoresFailure;

    onGetStoresSuccess = function onGetStoresSuccess(options, view_info) {
        var info, old_views, view_element, view_constructor, first_element = null;

        this.loading = false;
        this.error = false;

        old_views = this.viewsByName;
        this.viewsByName = {};

        for (info in view_info) {

            view_element = JSON.parse(view_info[info]);
            view_element.name = info;

            if (info in old_views) {
                this.viewsByName[info] = old_views[info];
                delete old_views[info];
            } else {
                view_constructor = Wirecloud.MarketManager.getMarketViewClass(view_element.type);
                this.viewsByName[info] = this.alternatives.createAlternative({alternative_constructor: view_constructor, containerOptions: {catalogue: this, marketplace_desc: view_element}});
            }

            this.number_of_alternatives += 1;
            if (first_element === null) {
                first_element = this.viewsByName[info];
            }
        }

        for (info in old_views) {
            this.alternatives.removeAlternative(old_views[info]);
            old_views[info].destroy();
        }

        if (this.alternatives.getCurrentAlternative() === this.emptyAlternative) {
            this.alternatives.showAlternative(this.viewsByName.local);
        }

        // Refresh wirecloud header as current marketplace may have been changed
        LayoutManagerFactory.getInstance().header.refresh();

        if (typeof options.onSuccess === 'function') {
            options.onSuccess();
        }
        if (typeof options.onComplete === 'function') {
            options.onComplete();
        }
    };

    onGetStoresFailure = function onGetStoresFailure(options, msg) {
        this.loading = false;
        this.error = true;

        LayoutManagerFactory.getInstance().header.refresh();
        if (typeof options.onFailure === 'function') {
            options.onSuccess();
        }
        if (typeof options.onFailure === 'function') {
            options.onComplete();
        }
    };

    MarketplaceView = function MarketplaceView(id, options) {
        options.id = 'marketplace';
        StyledElements.Alternative.call(this, id, options);

        this.viewsByName = {};
        this.alternatives = new StyledElements.StyledAlternatives();
        this.emptyAlternative = this.alternatives.createAlternative();
        this.alternatives.addEventListener('postTransition', function () {
            LayoutManagerFactory.getInstance().header.refresh();
        });
        this.appendChild(this.alternatives);

        this.marketMenu = new StyledElements.PopupMenu();
        this.marketMenu.append(new Wirecloud.ui.MarketplaceViewMenuItems(this));

        this.addEventListener('show', function (view) {
            if (!this.loading && !this.error) {
                view.alternatives.getCurrentAlternative().refresh_if_needed();
            }
        });

        this.number_of_alternatives = 0;
        this.loading = true;
        this.error = false;
        Wirecloud.MarketManager.getMarkets(onGetStoresSuccess.bind(this, {}), onGetStoresFailure.bind(this, {}));
    };

    MarketplaceView.prototype = new StyledElements.Alternative();

    MarketplaceView.prototype.view_name = 'marketplace';

    MarketplaceView.prototype.getBreadcrum = function () {
        var label, breadcrum;

        if (this.loading) {
            label = gettext('loading...');
        } else if (this.error) {
            label = gettext('list not available');
        } else if (this.number_of_alternatives > 0) {
            label = this.alternatives.getCurrentAlternative().getLabel();
        } else {
            label = gettext('no registered marketplace');
        }

        breadcrum = [
            {
                'label': 'marketplace'
            },
            {
                'label': label,
                'menu': this.marketMenu
            }
        ];

        // If no alternatives exist, it is no posible to have an extra breadcrum
        if (!this.loading && !this.error && this.number_of_alternatives > 0) {
            if (typeof this.alternatives.getCurrentAlternative().getExtraBreadcrum === 'function') {
                breadcrum = breadcrum.concat(this.alternatives.getCurrentAlternative().getExtraBreadcrum());
            }
        }
        return breadcrum;
    };

    MarketplaceView.prototype.refreshViewInfo = function refreshViewInfo(options) {

        if (this.loading) {
            return;
        }

        if (typeof options !== 'object') {
            options = {};
        }

        this.loading = true;
        LayoutManagerFactory.getInstance().header.refresh();

        this.number_of_alternatives = 0;

        Wirecloud.MarketManager.getMarkets(onGetStoresSuccess.bind(this, options), onGetStoresFailure.bind(this, options));
    };

    MarketplaceView.prototype.addMarket = function addMarket(market_info) {
        var view_constructor = Wirecloud.MarketManager.getMarketViewClass(market_info.type);
        this.viewsByName[market_info.name] = this.alternatives.createAlternative({alternative_constructor: view_constructor, containerOptions: {catalogue: this, marketplace_desc: market_info}});

        this.number_of_alternatives += 1;
        this.alternatives.showAlternative(this.viewsByName[market_info.name]);
    };

    window.MarketplaceView = MarketplaceView;
})();
<|endoftext|>


<commit_before>// @flow

const axios = require('axios');
const R = require('ramda');

const API_HOST = R.propOr(
  'http://gitlab',
  'GITLAB_API_HOST',
  process.env,
);
const API_TOKEN = R.propOr(
  'personal access token',
  'GITLAB_API_TOKEN',
  process.env,
);

const options = {
  baseURL: `${API_HOST}/api/v4/`,
  timeout: 2000,
  headers: {
    'Private-Token': API_TOKEN,
  },
};

const gitlabapi = axios.create(options);

class NetworkError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'NetworkError';
  }
}

class APIError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'GitLabAPIError';
  }
}

const getRequest = async (url: string): Object => {
  try {
    const response = await gitlabapi.get(url);
    return response.data;
  } catch (error) {
    if (error.response) {
      throw new APIError(
        R.pathOr(error.message, ['data', 'message'], error.response),
      );
    } else if (error.request) {
      throw new NetworkError(error.message);
    } else {
      throw error;
    }
  }
};

const getUserByUsername = async (username: string): Object => {
  try {
    const response = await gitlabapi.get('users', {
      params: {
        username,
      },
    });

    if (response.data.length === 0) {
      throw new APIError(`No user found with username: ${username}`);
    }

    return response.data[0];
  } catch (error) {
    if (error.response) {
      throw new APIError(
        R.pathOr(error.message, ['data', 'message'], error.response),
      );
    } else if (error.request) {
      throw new NetworkError(error.message);
    } else {
      throw error;
    }
  }
};

const getGroup = async (groupId: number): Object =>
  getRequest(`groups/${groupId}`);
const getProject = async (projectId: number): Object =>
  getRequest(`projects/${projectId}`);
const getUser = async (userId: number): Object => getRequest(`users/${userId}`);
const getSshKey = async (keyId: number): Object =>
  getRequest(`keys/${keyId}`);

module.exports = {
  getGroup,
  getProject,
  getUser,
  getSshKey,
  getUserByUsername,
};
<commit_msg>hotfix: increase gitlab timeout to 30secs<commit_after>// @flow

const axios = require('axios');
const R = require('ramda');

const API_HOST = R.propOr(
  'http://gitlab',
  'GITLAB_API_HOST',
  process.env,
);
const API_TOKEN = R.propOr(
  'personal access token',
  'GITLAB_API_TOKEN',
  process.env,
);

const options = {
  baseURL: `${API_HOST}/api/v4/`,
  timeout: 30000,
  headers: {
    'Private-Token': API_TOKEN,
  },
};

const gitlabapi = axios.create(options);

class NetworkError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'NetworkError';
  }
}

class APIError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'GitLabAPIError';
  }
}

const getRequest = async (url: string): Object => {
  try {
    const response = await gitlabapi.get(url);
    return response.data;
  } catch (error) {
    if (error.response) {
      throw new APIError(
        R.pathOr(error.message, ['data', 'message'], error.response),
      );
    } else if (error.request) {
      throw new NetworkError(error.message);
    } else {
      throw error;
    }
  }
};

const getUserByUsername = async (username: string): Object => {
  try {
    const response = await gitlabapi.get('users', {
      params: {
        username,
      },
    });

    if (response.data.length === 0) {
      throw new APIError(`No user found with username: ${username}`);
    }

    return response.data[0];
  } catch (error) {
    if (error.response) {
      throw new APIError(
        R.pathOr(error.message, ['data', 'message'], error.response),
      );
    } else if (error.request) {
      throw new NetworkError(error.message);
    } else {
      throw error;
    }
  }
};

const getGroup = async (groupId: number): Object =>
  getRequest(`groups/${groupId}`);
const getProject = async (projectId: number): Object =>
  getRequest(`projects/${projectId}`);
const getUser = async (userId: number): Object => getRequest(`users/${userId}`);
const getSshKey = async (keyId: number): Object =>
  getRequest(`keys/${keyId}`);

module.exports = {
  getGroup,
  getProject,
  getUser,
  getSshKey,
  getUserByUsername,
};
<|endoftext|>


<commit_before>app.controller('RidesController', ['$scope', 'RidesService', '$location', function($scope, RidesService, $location){

    var ride = {
        "num_passengers": 4,
        "start_latitude": 37.273485,
        "start_longitude": -76.719628,
        "end_latitude": 37.280893,
        "end_longitude": -76.719691,
        "phone": 15555555555
    };

    RidesService.createRide(ride)

		init = function() {
	      RidesService.getRides().then(function(data){
	          for (var i =0; i < data.rides.length; i++){
	              data.rides[i].start_address = ride.start_address ? ride.start_address : "Start Address Not Found";
	              data.rides[i].end_address = ride.end_address ? ride.end_address : "End Address Not Found";
                data.rides[i].message = data.rides[i].start_address + ": " + data.rides[i].id
	          };
	          $scope.rides = data.rides;
	    	});
        // alert($location.host());
    };

    init();

    $scope.deleteRide = function ( ride ) {
        if (confirm("Are you sure you want to delete this ride?")){
            del_index = $scope.rides.indexOf(ride);
            $scope.rides.splice(del_index,1);
            RidesService.deleteRide(ride.id);
        }
    };

}]);
<commit_msg>removed some unnecessary stuff<commit_after>app.controller('RidesController', ['$scope', 'RidesService', function($scope, RidesService){

    var ride = {
        "num_passengers": 4,
        "start_latitude": 37.273485,
        "start_longitude": -76.719628,
        "end_latitude": 37.280893,
        "end_longitude": -76.719691,
        "phone": 15555555555
    };

    RidesService.createRide(ride)

		init = function() {
	      RidesService.getRides().then(function(data){
	          for (var i =0; i < data.rides.length; i++){
	              data.rides[i].start_address = ride.start_address ? ride.start_address : "Start Address Not Found";
	              data.rides[i].end_address = ride.end_address ? ride.end_address : "End Address Not Found";
                data.rides[i].message = data.rides[i].start_address + ": " + data.rides[i].id
	          };
	          $scope.rides = data.rides;
	    	});
    };

    init();

    $scope.deleteRide = function ( ride ) {
        if (confirm("Are you sure you want to delete this ride?")){
            del_index = $scope.rides.indexOf(ride);
            $scope.rides.splice(del_index,1);
            RidesService.deleteRide(ride.id);
        }
    };

}]);
<|endoftext|>


<commit_before>"use strict";

let add = (map, data, file, filename) => {
  map.on("style.load", () => {
    map.addSource(filename, {
      "type": "geojson",
      "data": data
    });

   let style = {
     polygon: {
       visible: true,
       style: {
         "fill-color": "blue",
         "fill-opacity": 0.5
       },
       info: true,
       filter: [ "all" ]
     },
     line: {
       visible: true,
       style: {
         "line-color": "blue",
         "line-width": 8
       },
       info: true,
       filter: [ "all" ]
     },
     circle: {
       visible: false,
       style: {
         "circle-radius": 10,
         "circle-color": "blue",
         "circle-blur": 1
       },
       info: true,
       filter: [ "all" ]
     },
     icon: {
       visible: true,
       style: {
         "icon-image": "marker-15"
       },
       info: true,
       filter: [ "all" ]
     }
   };

   for(let key in file.style) {
     for(let item in file.style[key]) {
       style[key][item] = file.style[key][item];
     }
   }

   if(style.polygon.visible) {
      map.addLayer({
        "id": filename + "-polygon",
        "type": "fill",
        "source": filename,
        "paint": style.polygon.style,
        "interactive": style.polygon.info,
        "filter": style.polygon.filter
      });
    }

    if(style.line.visible) {
      map.addLayer({
        "id": filename + "-line",
        "type": "line",
        "source": filename,
        "layout": {
          "line-join": "round",
          "line-cap": "round"
        },
        "paint": style.line.style,
        "interactive": style.line.info,
        "filter": style.line.filter
      });
    }

    if(style.circle.visible) {
      map.addLayer({
        "id": filename + "-circle",
        "type": "circle",
        "source": filename,
        "paint": style.circle.style,
        "interactive": style.circle.info,
        "filter": style.circle.filter
      });
    }

    if(style.icon.visible) {
      map.addLayer({
        "id": filename + "-symbol",
        "type": "symbol",
        "source": filename,
        "layout": style.icon.style,
        "interactive": style.icon.info,
        "filter": style.icon.filter
      });
    }

    map.on('click', function (e) {
      map.featuresAt(e.point, {radius: 5}, function (err, features) {
        if(features.length == 0) {
          return;
        }

        let html = "";
        let info = features[0].properties;

        if(file.title == undefined && file.content == undefined) {
          for(let key in info) {
            html += "" + key + "： " + info[key] + "
";
          }
        }
        else {
          for(let key in file.title) {
            html += "" + file.title[key] + (file.title[key] == "" ? "" : "： ") + info[key] + "
"
          }
          for(let key in file.content) {
            html += "" + file.content[key] + (file.content[key] == "" ? "" : "： ") + info[key] + "
"
          }
        }

        new mapboxgl.Popup()
          .setLngLat(e.lngLat)
          .setHTML(html)
          .addTo(map);
        });
    });
  });
}

module.exports = (map, path, files) => {
  for(let i in files) {
    let fileName = Object.keys(files[i])[0];
    let file = files[i][fileName];
    if(path == undefined) {
      add(map, file.data, file, fileName);
    }
    else {
      let fileName = Object.keys(files[i])[0];
      let url = path.replace("[name]", fileName);
      let file = files[i][fileName];

      $.getJSON(url, (data) => {
        add(map, data, file, fileName);
      });
    }
  }
}
<commit_msg>remove  `on style.load`<commit_after>"use strict";

let add = (map, data, file, filename) => {
  map.addSource(filename, {
    "type": "geojson",
    "data": data
  });

 let style = {
   polygon: {
     visible: true,
     style: {
       "fill-color": "blue",
       "fill-opacity": 0.5
     },
     info: true,
     filter: [ "all" ]
   },
   line: {
     visible: true,
     style: {
       "line-color": "blue",
       "line-width": 8
     },
     info: true,
     filter: [ "all" ]
   },
   circle: {
     visible: false,
     style: {
       "circle-radius": 10,
       "circle-color": "blue",
       "circle-blur": 1
     },
     info: true,
     filter: [ "all" ]
   },
   icon: {
     visible: true,
     style: {
       "icon-image": "marker-15"
     },
     info: true,
     filter: [ "all" ]
   }
 };

 for(let key in file.style) {
   for(let item in file.style[key]) {
     style[key][item] = file.style[key][item];
   }
 }

 if(style.polygon.visible) {
    map.addLayer({
      "id": filename + "-polygon",
      "type": "fill",
      "source": filename,
      "paint": style.polygon.style,
      "interactive": style.polygon.info,
      "filter": style.polygon.filter
    });
  }

  if(style.line.visible) {
    map.addLayer({
      "id": filename + "-line",
      "type": "line",
      "source": filename,
      "layout": {
        "line-join": "round",
        "line-cap": "round"
      },
      "paint": style.line.style,
      "interactive": style.line.info,
      "filter": style.line.filter
    });
  }

  if(style.circle.visible) {
    map.addLayer({
      "id": filename + "-circle",
      "type": "circle",
      "source": filename,
      "paint": style.circle.style,
      "interactive": style.circle.info,
      "filter": style.circle.filter
    });
  }

  if(style.icon.visible) {
    map.addLayer({
      "id": filename + "-symbol",
      "type": "symbol",
      "source": filename,
      "layout": style.icon.style,
      "interactive": style.icon.info,
      "filter": style.icon.filter
    });
  }

  map.on('click', function (e) {
    map.featuresAt(e.point, {radius: 5}, function (err, features) {
      if(features.length == 0) {
        return;
      }

      let html = "";
      let info = features[0].properties;

      if(file.title == undefined && file.content == undefined) {
        for(let key in info) {
          html += "" + key + "： " + info[key] + "
";
        }
      }
      else {
        for(let key in file.title) {
          html += "" + file.title[key] + (file.title[key] == "" ? "" : "： ") + info[key] + "
"
        }
        for(let key in file.content) {
          html += "" + file.content[key] + (file.content[key] == "" ? "" : "： ") + info[key] + "
"
        }
      }

      new mapboxgl.Popup()
        .setLngLat(e.lngLat)
        .setHTML(html)
        .addTo(map);
      });
  });
}

module.exports = (map, path, files) => {
  for(let i in files) {
    let fileName = Object.keys(files[i])[0];
    let file = files[i][fileName];
    if(path == undefined) {
      add(map, file.data, file, fileName);
    }
    else {
      let fileName = Object.keys(files[i])[0];
      let url = path.replace("[name]", fileName);
      let file = files[i][fileName];

      $.getJSON(url, (data) => {
        add(map, data, file, fileName);
      });
    }
  }
}
<|endoftext|>


<commit_before>/* eslint-disable camelcase */
const { camelCase, pickBy, escape } = require('lodash')
const { newlineToBr } = require('../../../lib/text-formatting')

const config = require('../../../../config')
const labels = require('../labels')

const transformEntityLink = (entity, entityPath, noLinkText = null) => {
  return entity ? {
    url: `/${entityPath}/${entity.id}`,
    name: entity.name,
  } : noLinkText
}

const transformDocumentsLink = (archived_documents_url_path) => {
  if (archived_documents_url_path) {
    return {
      url: config.archivedDocumentsBaseUrl + archived_documents_url_path,
      name: 'View files and documents',
      hint: '(will open another website)',
      hintId: 'external-link-label',
    }
  }

  return { name: 'There are no files or documents' }
}

function transformInteractionResponseToViewRecord ({
  company,
  subject,
  notes,
  date,
  dit_adviser,
  service,
  service_delivery_status,
  grant_amount_offered,
  net_company_receipt,
  dit_team,
  contact,
  policy_areas,
  policy_issue_types,
  was_policy_feedback_provided,
  policy_feedback_notes,
  investment_project,
  communication_channel,
  event,
  kind,
  archived_documents_url_path,
}) {
  const defaultEventText = kind === 'service_delivery' ? 'No' : null
  const kindLabels = labels[camelCase(kind)]
  const displayPolicyAreas = (policy_areas || [])
    .map(policy_area => policy_area.name)
    .join(', ')

  const displayPolicyTypes = (policy_issue_types || [])
    .map(policy_type => policy_type.name)
    .join(', ')

  const transformed = {
    company: transformEntityLink(company, 'companies'),
    contact: transformEntityLink(contact, 'contacts'),
    dit_team,
    service,
    service_delivery_status,
    grant_amount_offered: grant_amount_offered ? {
      type: 'currency',
      name: grant_amount_offered,
    } : null,
    net_company_receipt: net_company_receipt ? {
      type: 'currency',
      name: net_company_receipt,
    } : null,
    subject,
    notes: newlineToBr(escape(notes)),
    date: {
      type: 'date',
      name: date,
    },
    dit_adviser,
    investment_project: transformEntityLink(investment_project, 'investment-projects'),
    event: transformEntityLink(event, 'events', defaultEventText),
    communication_channel: communication_channel,
    documents: transformDocumentsLink(archived_documents_url_path),
    policy_issue_types: displayPolicyTypes,
    policy_areas: displayPolicyAreas,
    policy_feedback_notes: newlineToBr(escape(notes)),
  }

  const result = {}
  Object.keys(transformed).forEach((key) => {
    const label = kindLabels[key]
    if (label) {
      result[label] = transformed[key]
    }
  })

  return pickBy(result)
}

module.exports = transformInteractionResponseToViewRecord
<commit_msg>Fix wrong notes being added to feedback notes field<commit_after>/* eslint-disable camelcase */
const { camelCase, pickBy, escape } = require('lodash')
const { newlineToBr } = require('../../../lib/text-formatting')

const config = require('../../../../config')
const labels = require('../labels')

const transformEntityLink = (entity, entityPath, noLinkText = null) => {
  return entity ? {
    url: `/${entityPath}/${entity.id}`,
    name: entity.name,
  } : noLinkText
}

const transformDocumentsLink = (archived_documents_url_path) => {
  if (archived_documents_url_path) {
    return {
      url: config.archivedDocumentsBaseUrl + archived_documents_url_path,
      name: 'View files and documents',
      hint: '(will open another website)',
      hintId: 'external-link-label',
    }
  }

  return { name: 'There are no files or documents' }
}

function transformInteractionResponseToViewRecord ({
  company,
  subject,
  notes,
  date,
  dit_adviser,
  service,
  service_delivery_status,
  grant_amount_offered,
  net_company_receipt,
  dit_team,
  contact,
  policy_areas,
  policy_issue_types,
  was_policy_feedback_provided,
  policy_feedback_notes,
  investment_project,
  communication_channel,
  event,
  kind,
  archived_documents_url_path,
}) {
  const defaultEventText = kind === 'service_delivery' ? 'No' : null
  const kindLabels = labels[camelCase(kind)]
  const displayPolicyAreas = (policy_areas || [])
    .map(policy_area => policy_area.name)
    .join(', ')

  const displayPolicyTypes = (policy_issue_types || [])
    .map(policy_type => policy_type.name)
    .join(', ')

  const transformed = {
    company: transformEntityLink(company, 'companies'),
    contact: transformEntityLink(contact, 'contacts'),
    dit_team,
    service,
    service_delivery_status,
    grant_amount_offered: grant_amount_offered ? {
      type: 'currency',
      name: grant_amount_offered,
    } : null,
    net_company_receipt: net_company_receipt ? {
      type: 'currency',
      name: net_company_receipt,
    } : null,
    subject,
    notes: newlineToBr(escape(notes)),
    date: {
      type: 'date',
      name: date,
    },
    dit_adviser,
    investment_project: transformEntityLink(investment_project, 'investment-projects'),
    event: transformEntityLink(event, 'events', defaultEventText),
    communication_channel: communication_channel,
    documents: transformDocumentsLink(archived_documents_url_path),
    policy_issue_types: displayPolicyTypes,
    policy_areas: displayPolicyAreas,
    policy_feedback_notes: newlineToBr(escape(policy_feedback_notes)),
  }

  const result = {}
  Object.keys(transformed).forEach((key) => {
    const label = kindLabels[key]
    if (label) {
      result[label] = transformed[key]
    }
  })

  return pickBy(result)
}

module.exports = transformInteractionResponseToViewRecord
<|endoftext|>


<commit_before>'use strict';

const safeBuffer = require('safe-buffer');
const zlib = require('zlib');

const bufferUtil = require('./BufferUtil');

const Buffer = safeBuffer.Buffer;

const AVAILABLE_WINDOW_BITS = [8, 9, 10, 11, 12, 13, 14, 15];
const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
const EMPTY_BLOCK = Buffer.from([0x00]);
const DEFAULT_WINDOW_BITS = 15;
const DEFAULT_MEM_LEVEL = 8;

/**
 * Per-message Deflate implementation.
 */
class PerMessageDeflate {
  constructor (options, isServer, maxPayload) {
    this._maxPayload = maxPayload | 0;
    this._options = options || {};
    this._threshold = this._options.threshold !== undefined
      ? this._options.threshold
      : 1024;
    this._isServer = !!isServer;
    this._deflate = null;
    this._inflate = null;

    this.params = null;
  }

  static get extensionName () {
    return 'permessage-deflate';
  }

  /**
   * Create extension parameters offer.
   *
   * @return {Object} Extension parameters
   * @public
   */
  offer () {
    const params = {};

    if (this._options.serverNoContextTakeover) {
      params.server_no_context_takeover = true;
    }
    if (this._options.clientNoContextTakeover) {
      params.client_no_context_takeover = true;
    }
    if (this._options.serverMaxWindowBits) {
      params.server_max_window_bits = this._options.serverMaxWindowBits;
    }
    if (this._options.clientMaxWindowBits) {
      params.client_max_window_bits = this._options.clientMaxWindowBits;
    } else if (this._options.clientMaxWindowBits == null) {
      params.client_max_window_bits = true;
    }

    return params;
  }

  /**
   * Accept extension offer.
   *
   * @param {Array} paramsList Extension parameters
   * @return {Object} Accepted configuration
   * @public
   */
  accept (paramsList) {
    paramsList = this.normalizeParams(paramsList);

    var params;
    if (this._isServer) {
      params = this.acceptAsServer(paramsList);
    } else {
      params = this.acceptAsClient(paramsList);
    }

    this.params = params;
    return params;
  }

  /**
   * Releases all resources used by the extension.
   *
   * @public
   */
  cleanup () {
    if (this._inflate) {
      if (this._inflate.writeInProgress) {
        this._inflate.pendingClose = true;
      } else {
        this._inflate.close();
        this._inflate = null;
      }
    }
    if (this._deflate) {
      if (this._deflate.writeInProgress) {
        this._deflate.pendingClose = true;
      } else {
        this._deflate.close();
        this._deflate = null;
      }
    }
  }

  /**
   * Accept extension offer from client.
   *
   * @param {Array} paramsList Extension parameters
   * @return {Object} Accepted configuration
   * @private
   */
  acceptAsServer (paramsList) {
    const accepted = {};
    const result = paramsList.some((params) => {
      if ((
        this._options.serverNoContextTakeover === false &&
        params.server_no_context_takeover
      ) || (
        this._options.serverMaxWindowBits === false &&
        params.server_max_window_bits
      ) || (
        typeof this._options.serverMaxWindowBits === 'number' &&
        typeof params.server_max_window_bits === 'number' &&
        this._options.serverMaxWindowBits > params.server_max_window_bits
      ) || (
        typeof this._options.clientMaxWindowBits === 'number' &&
        !params.client_max_window_bits
      )) {
        return;
      }

      if (
        this._options.serverNoContextTakeover ||
        params.server_no_context_takeover
      ) {
        accepted.server_no_context_takeover = true;
      }
      if (this._options.clientNoContextTakeover) {
        accepted.client_no_context_takeover = true;
      }
      if (
        this._options.clientNoContextTakeover !== false &&
        params.client_no_context_takeover
      ) {
        accepted.client_no_context_takeover = true;
      }
      if (typeof this._options.serverMaxWindowBits === 'number') {
        accepted.server_max_window_bits = this._options.serverMaxWindowBits;
      } else if (typeof params.server_max_window_bits === 'number') {
        accepted.server_max_window_bits = params.server_max_window_bits;
      }
      if (typeof this._options.clientMaxWindowBits === 'number') {
        accepted.client_max_window_bits = this._options.clientMaxWindowBits;
      } else if (
        this._options.clientMaxWindowBits !== false &&
        typeof params.client_max_window_bits === 'number'
      ) {
        accepted.client_max_window_bits = params.client_max_window_bits;
      }
      return true;
    });

    if (!result) throw new Error(`Doesn't support the offered configuration`);

    return accepted;
  }

  /**
   * Accept extension response from server.
   *
   * @param {Array} paramsList Extension parameters
   * @return {Object} Accepted configuration
   * @private
   */
  acceptAsClient (paramsList) {
    const params = paramsList[0];

    if (this._options.clientNoContextTakeover != null) {
      if (
        this._options.clientNoContextTakeover === false &&
        params.client_no_context_takeover
      ) {
        throw new Error('Invalid value for "client_no_context_takeover"');
      }
    }
    if (this._options.clientMaxWindowBits != null) {
      if (
        this._options.clientMaxWindowBits === false &&
        params.client_max_window_bits
      ) {
        throw new Error('Invalid value for "client_max_window_bits"');
      }
      if (
        typeof this._options.clientMaxWindowBits === 'number' && (
        !params.client_max_window_bits ||
        params.client_max_window_bits > this._options.clientMaxWindowBits
      )) {
        throw new Error('Invalid value for "client_max_window_bits"');
      }
    }

    return params;
  }

  /**
   * Normalize extensions parameters.
   *
   * @param {Array} paramsList Extension parameters
   * @return {Array} Normalized extensions parameters
   * @private
   */
  normalizeParams (paramsList) {
    return paramsList.map((params) => {
      Object.keys(params).forEach((key) => {
        var value = params[key];
        if (value.length > 1) {
          throw new Error(`Multiple extension parameters for ${key}`);
        }

        value = value[0];

        switch (key) {
          case 'server_no_context_takeover':
          case 'client_no_context_takeover':
            if (value !== true) {
              throw new Error(`invalid extension parameter value for ${key} (${value})`);
            }
            params[key] = true;
            break;
          case 'server_max_window_bits':
          case 'client_max_window_bits':
            if (typeof value === 'string') {
              value = parseInt(value, 10);
              if (!~AVAILABLE_WINDOW_BITS.indexOf(value)) {
                throw new Error(`invalid extension parameter value for ${key} (${value})`);
              }
            }
            if (!this._isServer && value === true) {
              throw new Error(`Missing extension parameter value for ${key}`);
            }
            params[key] = value;
            break;
          default:
            throw new Error(`Not defined extension parameter (${key})`);
        }
      });
      return params;
    });
  }

  /**
   * Decompress data.
   *
   * @param {Buffer} data Compressed data
   * @param {Boolean} fin Specifies whether or not this is the last fragment
   * @param {Function} callback Callback
   * @public
   */
  decompress (data, fin, callback) {
    const endpoint = this._isServer ? 'client' : 'server';

    if (!this._inflate) {
      const maxWindowBits = this.params[`${endpoint}_max_window_bits`];
      this._inflate = zlib.createInflateRaw({
        windowBits: typeof maxWindowBits === 'number' ? maxWindowBits : DEFAULT_WINDOW_BITS
      });
    }
    this._inflate.writeInProgress = true;

    var totalLength = 0;
    const buffers = [];
    var err;

    const onData = (data) => {
      totalLength += data.length;
      if (this._maxPayload < 1 || totalLength <= this._maxPayload) {
        return buffers.push(data);
      }

      err = new Error('max payload size exceeded');
      err.closeCode = 1009;
      this._inflate.reset();
    };

    const onError = (err) => {
      cleanup();
      callback(err);
    };

    const cleanup = () => {
      if (!this._inflate) return;

      this._inflate.removeListener('error', onError);
      this._inflate.removeListener('data', onData);
      this._inflate.writeInProgress = false;

      if (
        (fin && this.params[`${endpoint}_no_context_takeover`]) ||
        this._inflate.pendingClose
      ) {
        this._inflate.close();
        this._inflate = null;
      }
    };

    this._inflate.on('error', onError).on('data', onData);
    this._inflate.write(data);
    if (fin) this._inflate.write(TRAILER);

    this._inflate.flush(() => {
      cleanup();
      if (err) callback(err);
      else callback(null, bufferUtil.concat(buffers, totalLength));
    });
  }

  /**
   * Compress data.
   *
   * @param {Buffer} data Data to compress
   * @param {Boolean} fin Specifies whether or not this is the last fragment
   * @param {Function} callback Callback
   * @public
   */
  compress (data, fin, callback) {
    if (!data || data.length === 0) {
      process.nextTick(callback, null, EMPTY_BLOCK);
      return;
    }

    const endpoint = this._isServer ? 'server' : 'client';

    if (!this._deflate) {
      const maxWindowBits = this.params[`${endpoint}_max_window_bits`];
      this._deflate = zlib.createDeflateRaw({
        flush: zlib.Z_SYNC_FLUSH,
        windowBits: typeof maxWindowBits === 'number' ? maxWindowBits : DEFAULT_WINDOW_BITS,
        memLevel: this._options.memLevel || DEFAULT_MEM_LEVEL
      });
    }
    this._deflate.writeInProgress = true;

    var totalLength = 0;
    const buffers = [];

    const onData = (data) => {
      totalLength += data.length;
      buffers.push(data);
    };

    const onError = (err) => {
      cleanup();
      callback(err);
    };

    const cleanup = () => {
      if (!this._deflate) return;

      this._deflate.removeListener('error', onError);
      this._deflate.removeListener('data', onData);
      this._deflate.writeInProgress = false;

      if (
        (fin && this.params[`${endpoint}_no_context_takeover`]) ||
        this._deflate.pendingClose
      ) {
        this._deflate.close();
        this._deflate = null;
      }
    };

    this._deflate.on('error', onError).on('data', onData);
    this._deflate.write(data);
    this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
      cleanup();
      var data = bufferUtil.concat(buffers, totalLength);
      if (fin) data = data.slice(0, data.length - 4);
      callback(null, data);
    });
  }
}

module.exports = PerMessageDeflate;
<commit_msg>[minor] Merge two consecutive if statements<commit_after>'use strict';

const safeBuffer = require('safe-buffer');
const zlib = require('zlib');

const bufferUtil = require('./BufferUtil');

const Buffer = safeBuffer.Buffer;

const AVAILABLE_WINDOW_BITS = [8, 9, 10, 11, 12, 13, 14, 15];
const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
const EMPTY_BLOCK = Buffer.from([0x00]);
const DEFAULT_WINDOW_BITS = 15;
const DEFAULT_MEM_LEVEL = 8;

/**
 * Per-message Deflate implementation.
 */
class PerMessageDeflate {
  constructor (options, isServer, maxPayload) {
    this._maxPayload = maxPayload | 0;
    this._options = options || {};
    this._threshold = this._options.threshold !== undefined
      ? this._options.threshold
      : 1024;
    this._isServer = !!isServer;
    this._deflate = null;
    this._inflate = null;

    this.params = null;
  }

  static get extensionName () {
    return 'permessage-deflate';
  }

  /**
   * Create extension parameters offer.
   *
   * @return {Object} Extension parameters
   * @public
   */
  offer () {
    const params = {};

    if (this._options.serverNoContextTakeover) {
      params.server_no_context_takeover = true;
    }
    if (this._options.clientNoContextTakeover) {
      params.client_no_context_takeover = true;
    }
    if (this._options.serverMaxWindowBits) {
      params.server_max_window_bits = this._options.serverMaxWindowBits;
    }
    if (this._options.clientMaxWindowBits) {
      params.client_max_window_bits = this._options.clientMaxWindowBits;
    } else if (this._options.clientMaxWindowBits == null) {
      params.client_max_window_bits = true;
    }

    return params;
  }

  /**
   * Accept extension offer.
   *
   * @param {Array} paramsList Extension parameters
   * @return {Object} Accepted configuration
   * @public
   */
  accept (paramsList) {
    paramsList = this.normalizeParams(paramsList);

    var params;
    if (this._isServer) {
      params = this.acceptAsServer(paramsList);
    } else {
      params = this.acceptAsClient(paramsList);
    }

    this.params = params;
    return params;
  }

  /**
   * Releases all resources used by the extension.
   *
   * @public
   */
  cleanup () {
    if (this._inflate) {
      if (this._inflate.writeInProgress) {
        this._inflate.pendingClose = true;
      } else {
        this._inflate.close();
        this._inflate = null;
      }
    }
    if (this._deflate) {
      if (this._deflate.writeInProgress) {
        this._deflate.pendingClose = true;
      } else {
        this._deflate.close();
        this._deflate = null;
      }
    }
  }

  /**
   * Accept extension offer from client.
   *
   * @param {Array} paramsList Extension parameters
   * @return {Object} Accepted configuration
   * @private
   */
  acceptAsServer (paramsList) {
    const accepted = {};
    const result = paramsList.some((params) => {
      if ((
        this._options.serverNoContextTakeover === false &&
        params.server_no_context_takeover
      ) || (
        this._options.serverMaxWindowBits === false &&
        params.server_max_window_bits
      ) || (
        typeof this._options.serverMaxWindowBits === 'number' &&
        typeof params.server_max_window_bits === 'number' &&
        this._options.serverMaxWindowBits > params.server_max_window_bits
      ) || (
        typeof this._options.clientMaxWindowBits === 'number' &&
        !params.client_max_window_bits
      )) {
        return;
      }

      if (
        this._options.serverNoContextTakeover ||
        params.server_no_context_takeover
      ) {
        accepted.server_no_context_takeover = true;
      }
      if (this._options.clientNoContextTakeover || (
        this._options.clientNoContextTakeover !== false &&
        params.client_no_context_takeover
      )) {
        accepted.client_no_context_takeover = true;
      }
      if (typeof this._options.serverMaxWindowBits === 'number') {
        accepted.server_max_window_bits = this._options.serverMaxWindowBits;
      } else if (typeof params.server_max_window_bits === 'number') {
        accepted.server_max_window_bits = params.server_max_window_bits;
      }
      if (typeof this._options.clientMaxWindowBits === 'number') {
        accepted.client_max_window_bits = this._options.clientMaxWindowBits;
      } else if (
        this._options.clientMaxWindowBits !== false &&
        typeof params.client_max_window_bits === 'number'
      ) {
        accepted.client_max_window_bits = params.client_max_window_bits;
      }
      return true;
    });

    if (!result) throw new Error("Doesn't support the offered configuration");

    return accepted;
  }

  /**
   * Accept extension response from server.
   *
   * @param {Array} paramsList Extension parameters
   * @return {Object} Accepted configuration
   * @private
   */
  acceptAsClient (paramsList) {
    const params = paramsList[0];

    if (this._options.clientNoContextTakeover != null) {
      if (
        this._options.clientNoContextTakeover === false &&
        params.client_no_context_takeover
      ) {
        throw new Error('Invalid value for "client_no_context_takeover"');
      }
    }
    if (this._options.clientMaxWindowBits != null) {
      if (
        this._options.clientMaxWindowBits === false &&
        params.client_max_window_bits
      ) {
        throw new Error('Invalid value for "client_max_window_bits"');
      }
      if (
        typeof this._options.clientMaxWindowBits === 'number' && (
        !params.client_max_window_bits ||
        params.client_max_window_bits > this._options.clientMaxWindowBits
      )) {
        throw new Error('Invalid value for "client_max_window_bits"');
      }
    }

    return params;
  }

  /**
   * Normalize extensions parameters.
   *
   * @param {Array} paramsList Extension parameters
   * @return {Array} Normalized extensions parameters
   * @private
   */
  normalizeParams (paramsList) {
    return paramsList.map((params) => {
      Object.keys(params).forEach((key) => {
        var value = params[key];
        if (value.length > 1) {
          throw new Error(`Multiple extension parameters for ${key}`);
        }

        value = value[0];

        switch (key) {
          case 'server_no_context_takeover':
          case 'client_no_context_takeover':
            if (value !== true) {
              throw new Error(`invalid extension parameter value for ${key} (${value})`);
            }
            params[key] = true;
            break;
          case 'server_max_window_bits':
          case 'client_max_window_bits':
            if (typeof value === 'string') {
              value = parseInt(value, 10);
              if (!~AVAILABLE_WINDOW_BITS.indexOf(value)) {
                throw new Error(`invalid extension parameter value for ${key} (${value})`);
              }
            }
            if (!this._isServer && value === true) {
              throw new Error(`Missing extension parameter value for ${key}`);
            }
            params[key] = value;
            break;
          default:
            throw new Error(`Not defined extension parameter (${key})`);
        }
      });
      return params;
    });
  }

  /**
   * Decompress data.
   *
   * @param {Buffer} data Compressed data
   * @param {Boolean} fin Specifies whether or not this is the last fragment
   * @param {Function} callback Callback
   * @public
   */
  decompress (data, fin, callback) {
    const endpoint = this._isServer ? 'client' : 'server';

    if (!this._inflate) {
      const maxWindowBits = this.params[`${endpoint}_max_window_bits`];
      this._inflate = zlib.createInflateRaw({
        windowBits: typeof maxWindowBits === 'number' ? maxWindowBits : DEFAULT_WINDOW_BITS
      });
    }
    this._inflate.writeInProgress = true;

    var totalLength = 0;
    const buffers = [];
    var err;

    const onData = (data) => {
      totalLength += data.length;
      if (this._maxPayload < 1 || totalLength <= this._maxPayload) {
        return buffers.push(data);
      }

      err = new Error('max payload size exceeded');
      err.closeCode = 1009;
      this._inflate.reset();
    };

    const onError = (err) => {
      cleanup();
      callback(err);
    };

    const cleanup = () => {
      if (!this._inflate) return;

      this._inflate.removeListener('error', onError);
      this._inflate.removeListener('data', onData);
      this._inflate.writeInProgress = false;

      if (
        (fin && this.params[`${endpoint}_no_context_takeover`]) ||
        this._inflate.pendingClose
      ) {
        this._inflate.close();
        this._inflate = null;
      }
    };

    this._inflate.on('error', onError).on('data', onData);
    this._inflate.write(data);
    if (fin) this._inflate.write(TRAILER);

    this._inflate.flush(() => {
      cleanup();
      if (err) callback(err);
      else callback(null, bufferUtil.concat(buffers, totalLength));
    });
  }

  /**
   * Compress data.
   *
   * @param {Buffer} data Data to compress
   * @param {Boolean} fin Specifies whether or not this is the last fragment
   * @param {Function} callback Callback
   * @public
   */
  compress (data, fin, callback) {
    if (!data || data.length === 0) {
      process.nextTick(callback, null, EMPTY_BLOCK);
      return;
    }

    const endpoint = this._isServer ? 'server' : 'client';

    if (!this._deflate) {
      const maxWindowBits = this.params[`${endpoint}_max_window_bits`];
      this._deflate = zlib.createDeflateRaw({
        flush: zlib.Z_SYNC_FLUSH,
        windowBits: typeof maxWindowBits === 'number' ? maxWindowBits : DEFAULT_WINDOW_BITS,
        memLevel: this._options.memLevel || DEFAULT_MEM_LEVEL
      });
    }
    this._deflate.writeInProgress = true;

    var totalLength = 0;
    const buffers = [];

    const onData = (data) => {
      totalLength += data.length;
      buffers.push(data);
    };

    const onError = (err) => {
      cleanup();
      callback(err);
    };

    const cleanup = () => {
      if (!this._deflate) return;

      this._deflate.removeListener('error', onError);
      this._deflate.removeListener('data', onData);
      this._deflate.writeInProgress = false;

      if (
        (fin && this.params[`${endpoint}_no_context_takeover`]) ||
        this._deflate.pendingClose
      ) {
        this._deflate.close();
        this._deflate = null;
      }
    };

    this._deflate.on('error', onError).on('data', onData);
    this._deflate.write(data);
    this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
      cleanup();
      var data = bufferUtil.concat(buffers, totalLength);
      if (fin) data = data.slice(0, data.length - 4);
      callback(null, data);
    });
  }
}

module.exports = PerMessageDeflate;
<|endoftext|>


<commit_before>/* medea.js - Open Source, High-Performance 3D Engine based on WebGL.
 *
 * (c) 2011-2013, Alexander C. Gessler
 *  https://github.com/acgessler/medea.js
 *
 * Made available under the terms and conditions of a 3-clause BSD license.
 *
 */

medealib.define('renderqueue',['renderstate'],function(medealib, undefined) {
	"use strict";
	var medea = this;

	//
	this.RENDERQUEUE_FIRST = 0;

	this.RENDERQUEUE_LIGHT = 8;
	this.RENDERQUEUE_DEFAULT_EARLY = 10;
	this.RENDERQUEUE_DEFAULT = 11;
	this.RENDERQUEUE_DEFAULT_LATE = 12;

	// Since background drawing (i.e. skybox) typically runs on the
	// full screen size with depth_write=false, depth_test=true and
	// therefore overrides geometry that doesn't leave traces in
	// the depth buffer, it need be rendered before alpha geometry.
	this.RENDERQUEUE_BACKGROUND = 13;

	this.RENDERQUEUE_ALPHA_EARLY = 14;
	this.RENDERQUEUE_ALPHA = 15;
	this.RENDERQUEUE_ALPHA_LATE = 16;

	this.RENDERQUEUE_LAST = 19;

	// class DistanceSorter
	this.DistanceSorter = medealib.Class.extend({

		Run : function(entries) {
			entries.sort(function(a,b) {
				return a.DistanceEstimate() - b.DistanceEstimate();
			});
		}
	});

	// class MaterialSorter
	this.MaterialSorter = medealib.Class.extend({

		Run : function(entries) {
			entries.sort(function(a,b) {
				return a.MaterialId() - b.MaterialId();
			});
		}
	});

	// class NoSorter
	this.NoSorter = medealib.Class.extend({

		Run : function(entries) {
			// intentionally a no-op
		}
	});

	// class RenderQueue
	this.RenderQueue = medealib.Class.extend({

		init: function(sorter,default_state) {
			this.entries = [];
			this.sorter = sorter;
			this.default_state = default_state;
		},

		Push: function(e) {
			this.entries.push(e);
		},

		Flush: function(renderer, statepool) {
			medea.SetDefaultState(this.default_state || {},statepool);

			if (this.sorter) {
				this.sorter.Run(this.entries);
			}

			this.entries.forEach(function(e) {
				e.Draw(renderer, statepool);
			});
			this.entries = [];
		},

		Sorter : medealib.Property('sorter'),
		DefaultState : medealib.Property('default_state'),

		GetEntries : function() {
			return this.entries;
		}
	});

	// class RenderQueueManager
	this.RenderQueueManager = medealib.Class.extend({

		init : function(name) {
			// allocates queues, by default all queues have no further configuration
			// setting sorters and default states is done by the renderer.
			this.queues = new Array(medea.RENDERQUEUE_LAST+1);
			for(var i = 0, l = this.queues.length; i < l; ++i) {
				this.queues[i] = new medea.RenderQueue();
			}
		},

		Push : function(idx,renderable) {
// #ifdef DEBUG
			if (idx < 0 || idx >= this.queues.length) {
				medealib.NotifyFatal("render queue does not exist: " + idx);
				return;
			}
// #endif

			this.queues[idx].Push(renderable);
		},

		Flush : function(renderer, statepool) {
			this.queues.forEach(function(e) {
				e.Flush(renderer, statepool);
			});
		},

		// supply a custom queue implementation
		SetQueueImpl : function(idx,queue) {
			this.queues[idx] = queue;
		},

		GetQueues : function() {
			return this.queues;
		}
	});

	medea.CreateRenderQueueManager = function() {
		return new medea.RenderQueueManager();
	}
});
<commit_msg>RenderQueue: for rendering opaque objects, do a secondary sort by distance front-to-back.<commit_after>/* medea.js - Open Source, High-Performance 3D Engine based on WebGL.
 *
 * (c) 2011-2013, Alexander C. Gessler
 *  https://github.com/acgessler/medea.js
 *
 * Made available under the terms and conditions of a 3-clause BSD license.
 *
 */

medealib.define('renderqueue',['renderstate'],function(medealib, undefined) {
	"use strict";
	var medea = this;

	//
	this.RENDERQUEUE_FIRST = 0;

	this.RENDERQUEUE_LIGHT = 8;
	this.RENDERQUEUE_DEFAULT_EARLY = 10;
	this.RENDERQUEUE_DEFAULT = 11;
	this.RENDERQUEUE_DEFAULT_LATE = 12;

	// Since background drawing (i.e. skybox) typically runs on the
	// full screen size with depth_write=false, depth_test=true and
	// therefore overrides geometry that doesn't leave traces in
	// the depth buffer, it need be rendered before alpha geometry.
	this.RENDERQUEUE_BACKGROUND = 13;

	this.RENDERQUEUE_ALPHA_EARLY = 14;
	this.RENDERQUEUE_ALPHA = 15;
	this.RENDERQUEUE_ALPHA_LATE = 16;

	this.RENDERQUEUE_LAST = 19;

	// class DistanceSorter (back-to-front)
	this.DistanceSorter = medealib.Class.extend({

		Run : function(entries) {
			entries.sort(function(a,b) {
				return b.DistanceEstimate() - a.DistanceEstimate();
			});
		}
	});

	// class MaterialSorter (secondary sort by distance, front-to-back)
	this.MaterialSorter = medealib.Class.extend({

		Run : function(entries) {
			entries.sort(function(a, b) {
				var d = a.MaterialId() - b.MaterialId();
				if (d !== 0) {
					return d;
				}
				return a.DistanceEstimate() - b.DistanceEstimate();
			});
		}
	});

	// class NoSorter
	this.NoSorter = medealib.Class.extend({

		Run : function(entries) {
			// intentionally a no-op
		}
	});

	// class RenderQueue
	this.RenderQueue = medealib.Class.extend({

		init: function(sorter,default_state) {
			this.entries = [];
			this.sorter = sorter;
			this.default_state = default_state;
		},

		Push: function(e) {
			this.entries.push(e);
		},

		Flush: function(renderer, statepool) {
			medea.SetDefaultState(this.default_state || {},statepool);

			if (this.sorter) {
				this.sorter.Run(this.entries);
			}

			this.entries.forEach(function(e) {
				e.Draw(renderer, statepool);
			});
			this.entries = [];
		},

		Sorter : medealib.Property('sorter'),
		DefaultState : medealib.Property('default_state'),

		GetEntries : function() {
			return this.entries;
		}
	});

	// class RenderQueueManager
	this.RenderQueueManager = medealib.Class.extend({

		init : function(name) {
			// allocates queues, by default all queues have no further configuration
			// setting sorters and default states is done by the renderer.
			this.queues = new Array(medea.RENDERQUEUE_LAST+1);
			for(var i = 0, l = this.queues.length; i < l; ++i) {
				this.queues[i] = new medea.RenderQueue();
			}
		},

		Push : function(idx,renderable) {
// #ifdef DEBUG
			if (idx < 0 || idx >= this.queues.length) {
				medealib.NotifyFatal("render queue does not exist: " + idx);
				return;
			}
// #endif

			this.queues[idx].Push(renderable);
		},

		Flush : function(renderer, statepool) {
			this.queues.forEach(function(e) {
				e.Flush(renderer, statepool);
			});
		},

		// supply a custom queue implementation
		SetQueueImpl : function(idx,queue) {
			this.queues[idx] = queue;
		},

		GetQueues : function() {
			return this.queues;
		}
	});

	medea.CreateRenderQueueManager = function() {
		return new medea.RenderQueueManager();
	}
});
<|endoftext|>


<commit_before>'use strict';

function globalModule_Try(moduleString) {
	try {
		return require(moduleString);
	} catch (exception) {
		console.log("FAILED TO LOAD: \"" + moduleString + "\"");
		console.log(exception);
		return null;
	}
}

function dump_debug_string(string) {
	var fileSystem_Module = globalModule_Try('fs');
	var inHouseFileHandle = fileSystem_Module.openSync("./local_debug_dump.txt", 'a');
	fileSystem_Module.writeSync(inHouseFileHandle, string);
	fileSystem_Module.closeSync(inHouseFileHandle);
}

function message_locator_service(mainMessage) {
	var path_Module = globalModule_Try('path');
	var stackTrace_Module = globalModule_Try('stack-trace');
	var currentFrame = stackTrace_Module.get()[1];
	console.log(mainMessage + " >>> \"" + path_Module.basename(currentFrame.getFileName()) + ":" +
	    currentFrame.getLineNumber() + "\"\n");
}

function spot_the_head(htmlLineArray) {
	var headAreaMark_Array = [ -1, -1 ];
	var headMark_RegExp = new RegExp("<\\s*\\/?\\s*head\\s*>", "i");
	for (var i = 0; i < htmlLineArray.length; i++) {
		if (headMark_RegExp.exec(htmlLineArray[i]) !== null) {
			if (headAreaMark_Array[0] === -1) {
				headAreaMark_Array[0] = i;
			} else {
				headAreaMark_Array[1] = i;
				break;
			}
		}
	}
	if (headAreaMark_Array[0] === -1 || headAreaMark_Array[1] === -1) {
		message_locator_service("HEAD AREA BOUNDRIES BUGGY OR NOT FOUND AT ALL...!");
		return false;
	} else {
		return headAreaMark_Array;
	}
}

function carriage_return_needed() {
	var os_Module = globalModule_Try('os');
	var windowsSpotter_RegExp = new RegExp("windows", "i");
	if (windowsSpotter_RegExp.exec(os_Module.type()) !== null) {
		return true;
	} else {
		return false;
	}
}

function end_of_line_clean_save(fileName, array, carriageReturn) {
	var carriageReturnString = "";
	if (carriageReturn) {
		carriageReturnString = "\r";
	}
	var fileSystem_Module = globalModule_Try('fs');
	var currentFileHandle = fileSystem_Module.openSync(fileName, 'w');

	var lineSpotter_RegExp = new RegExp("^([\\x20\\x09]*)(.*)\\x0d*$", "i");
	var initialLineResultArray = lineSpotter_RegExp.exec(array[0]);
	if (initialLineResultArray !== null) {
		if (initialLineResultArray[2]) {
			fileSystem_Module.writeSync(currentFileHandle, initialLineResultArray[1] + initialLineResultArray[2] +
			    carriageReturnString + "\n");
		}
	} else {
		message_locator_service("MISSED THE INITIAL LINE...!");
		return false;
	}
	for (var j = 1; j < (array.length - 1); j++) {
		var lineResultArray = lineSpotter_RegExp.exec(array[j]);
		if (lineResultArray !== null) {
			if (j === (array.length - 2)) {
				var nextToLast_ResultArray = lineSpotter_RegExp.exec(array[array.length - 1]);
				if (!nextToLast_ResultArray[2]) {
					fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2]);
				} else {
					fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2] + carriageReturnString +
					    "\n");
				}
			} else {
				fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2] + carriageReturnString +
				    "\n");
			}
		} else {
			message_locator_service("MISSED A LINE...!");
			return false;
		}
	}
	var finalLineResultArray = lineSpotter_RegExp.exec(array[array.length - 1]);
	if (finalLineResultArray !== null) {
		if (finalLineResultArray[2]) {
			fileSystem_Module.writeSync(currentFileHandle, finalLineResultArray[1] + finalLineResultArray[2]);
		}
	} else {
		message_locator_service("MISSED THE FINAL LINE...!");
		return false;
	}
	fileSystem_Module.closeSync(currentFileHandle);
	return true;
}

function array_from_file_delete(entire_fileName) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(entire_fileName)) {
		var targetFile_LineArray = fileSystem_Module.readFileSync(entire_fileName, 'utf8', 'r').toString().split('\n');
		fileSystem_Module.unlinkSync(entire_fileName);
		return targetFile_LineArray;
	} else {
		message_locator_service("TARGET FILE DOES NOT EXIST...!");
		return false;
	}
}

function array_from_file(entire_fileName) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(entire_fileName)) {
		var targetFile_LineArray = fileSystem_Module.readFileSync(entire_fileName, 'utf8', 'r').toString().split('\n');
		return targetFile_LineArray;
	} else {
		message_locator_service("TARGET FILE DOES NOT EXIST...!");
		return false;
	}
}

// Switching html head area to minified targets...
function toMin(headStart, headEnd, carriageReturn, contentArray) {
	var changed = false;
	var hasMin_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)(?:\\.min)+(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	var carelessAboutMin_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	for (var i = (headStart + 1); i < headEnd; i++) {
		if (hasMin_RegExp.exec(contentArray[i]) === null) {
			var regExp_ResultArray = carelessAboutMin_RegExp.exec(contentArray[i]);
			if (regExp_ResultArray !== null) {
				contentArray[i] = regExp_ResultArray[1] + ".min" + regExp_ResultArray[2] + carriageReturn;
				if (!changed) {
					changed = true;
				}
			}
		}
	}
	if (changed) {
		return contentArray;
	} else {
		return false;
	}
}

// Switching html head area to regular targets...
function toRegular(headStart, headEnd, carriageReturn, contentArray) {
	var changed = false;
	var minSuspect_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)\\.min(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	for (var i = (headStart + 1); i < headEnd; i++) {
		var regExp_ResultArray = minSuspect_RegExp.exec(contentArray[i]);
		if (regExp_ResultArray !== null) {
			contentArray[i] = regExp_ResultArray[1] + regExp_ResultArray[2] + carriageReturn;
			if (!changed) {
				changed = true;
			}
		}
	}
	if (changed) {
		return contentArray;
	} else {
		return false;
	}
}

function delete_writingArray_ToFile(fileName, array) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(fileName)) {
		fileSystem_Module.unlinkSync(fileName);
	}
	var inHouseFileHandle = fileSystem_Module.openSync(fileName, 'w');
	for (var i = 0; i < (array.length - 1); i++) {
		fileSystem_Module.writeSync(inHouseFileHandle, array[i] + "\n");
	}
	if (array[array.length - 1]) {
		fileSystem_Module.writeSync(inHouseFileHandle, array[array.length - 1]);
	}
	fileSystem_Module.closeSync(inHouseFileHandle);
}

module.exports = {
  casual__options__servant : function(options_object, option_request) {
	  var top_level_options_reference_object = {
	    action : [ 'switch', 'clean' ],
	    chattiness : [ 'true', 'false' ],
	    direction : [ 'min', 'regular' ],
	    file_source : [ 'wildcard', 'list' ],
	  };
	  for ( var item in options_object) {
		  if (item === option_request) {
			  console.log(item + ": \"" + options_object[item] + "\"");
		  } else {

		  }
	  }
  },

  add_on_options__servant : function(global_object) {
	  var noisy = true;
	  var global_options_object = global_object.data.options;
	  var global_add_on_options_object = {
		  chattiness : [ 'true', 'false' ]
	  };
	  if (global_options_object !== undefined) {
		  if (noisy) {
			  console.log(">>> Options section found... Doing further checking... <<<");
		  }
		  for ( var item in global_add_on_options_object) {
			  if (global_options_object.hasOwnProperty(item)) {
				  var contains_valid_value = false;
				  for (var i = 0; i < global_add_on_options_object[item].length; i++) {
					  if (global_add_on_options_object[item].includes(global_options_object[item])) {
						  contains_valid_value = true;
						  break;
					  }
				  }
				  if (!contains_valid_value) {
					  console.log("\"" + global_options_object[item] + "\" IS NOT A VALID OPTION WITH \"" + item + "\" ...!");
					  return false;
				  }
			  } else {
				  if (noisy) {
					  console.log("MISSING OBJECTS OPTIONS PROPERTY: \"" + item + "\" ...!");
				  }
				  return false;
			  }
		  }
		  return true;
	  } else {
		  console.log(">>> NO VALID OPTIONS SECTION FOUND...! <<<");
		  return false;
	  }
  },

  private_action_checker : function(global_object, reference_object, noisy) {
	  var global_options_object = global_object.data.options;
	  if (global_options_object !== undefined) {
		  if (noisy) {
			  console.log(">>> Options section found... Doing further checking... <<<");
		  }
		  for ( var item in reference_object) {
			  if (global_options_object.hasOwnProperty(item)) {
				  var contains_valid_value = false;
				  for (var i = 0; i < reference_object[item].length; i++) {
					  if (reference_object[item].includes(global_options_object[item])) {
						  contains_valid_value = true;
						  break;
					  }
				  }
				  if (!contains_valid_value) {
					  console.log("\"" + global_options_object[item] + "\" IS NOT A VALID OPTION WITH \"" + item + "\" ...!");
					  return false;
				  }
			  } else {
				  if (noisy) {
					  console.log("MISSING OBJECTS OPTIONS PROPERTY: \"" + item + "\" ...!");
				  }
				  return false;
			  }
		  }
		  return true;
	  } else {
		  console.log(">>> NO VALID OPTIONS SECTION FOUND...! <<<");
		  return false;
	  }
  },

  process_wildcard_input : function(source, directory) {
	  var wildcard_extractor_RegExp = new RegExp("^\\*(.+)$");
	  var result_array = wildcard_extractor_RegExp.exec(source);
	  var final_files_array = [];
	  if (result_array) {
		  var tail_string = result_array[1];
		  var prepared_tail = tail_string.replace(/\./ig, "\\.");
		  var wildcard_RegExp = new RegExp("^(.+" + prepared_tail + ")$", "i");
		  var fileSystem_Module = globalModule_Try('fs');
		  var raw_file_array = fileSystem_Module.readdirSync(directory);
		  var targets_file_array = [];
		  for (var i = 0; i < raw_file_array.length; i++) {
			  var single_file_result_array = wildcard_RegExp.exec(raw_file_array[i]);
			  if (single_file_result_array) {
				  final_files_array.push(directory + single_file_result_array[1]);
			  }
		  }
		  return final_files_array;
	  } else {
		  message_locator_service("NO VALID WILDCARD FOUND...!");
		  return false;
	  }
  },

  toggle_all_head_links : function(direction, file) {
	  var pointToMin = false;
	  if (direction === 'min') {
		  pointToMin = true;
	  }
	  var targetFile_LineArray = array_from_file(file);
	  if (targetFile_LineArray) {
		  var windowsNeeded_carriageReturn = "";
		  if (carriage_return_needed) {
			  windowsNeeded_carriageReturn = "\r";
		  }
		  var headStart = spot_the_head(targetFile_LineArray)[0];
		  var headEnd = spot_the_head(targetFile_LineArray)[1];

		  // Actual array manipulation...
		  if (pointToMin) {
			  targetFile_LineArray = toMin(headStart, headEnd, windowsNeeded_carriageReturn, targetFile_LineArray);
			  if (targetFile_LineArray) {
				  delete_writingArray_ToFile(file, targetFile_LineArray);
				  return true;
			  } else {
				  return true;
			  }
		  } else {
			  targetFile_LineArray = toRegular(headStart, headEnd, windowsNeeded_carriageReturn, targetFile_LineArray);
			  if (targetFile_LineArray) {
				  delete_writingArray_ToFile(file, targetFile_LineArray);
				  return true;
			  } else {
				  return true;
			  }
		  }
	  } else {
		  message_locator_service("FAILED TO GET VALID DATA ARRAY...!");
		  return false;
	  }
  },

  end_of_line_refresh : function(file) {
	  var targetFile_LineArray = array_from_file_delete(file);
	  if (targetFile_LineArray) {
		  return end_of_line_clean_save(file, targetFile_LineArray, carriage_return_needed());
	  } else {
		  message_locator_service("FAILED TO GET VALID DATA ARRAY...!");
		  return false;
	  }
  }
};
<commit_msg>Added if & else... - MH - pT<commit_after>'use strict';

function globalModule_Try(moduleString) {
	try {
		return require(moduleString);
	} catch (exception) {
		console.log("FAILED TO LOAD: \"" + moduleString + "\"");
		console.log(exception);
		return null;
	}
}

function dump_debug_string(string) {
	var fileSystem_Module = globalModule_Try('fs');
	var inHouseFileHandle = fileSystem_Module.openSync("./local_debug_dump.txt", 'a');
	fileSystem_Module.writeSync(inHouseFileHandle, string);
	fileSystem_Module.closeSync(inHouseFileHandle);
}

function message_locator_service(mainMessage) {
	var path_Module = globalModule_Try('path');
	var stackTrace_Module = globalModule_Try('stack-trace');
	var currentFrame = stackTrace_Module.get()[1];
	console.log(mainMessage + " >>> \"" + path_Module.basename(currentFrame.getFileName()) + ":" +
	    currentFrame.getLineNumber() + "\"\n");
}

function spot_the_head(htmlLineArray) {
	var headAreaMark_Array = [ -1, -1 ];
	var headMark_RegExp = new RegExp("<\\s*\\/?\\s*head\\s*>", "i");
	for (var i = 0; i < htmlLineArray.length; i++) {
		if (headMark_RegExp.exec(htmlLineArray[i]) !== null) {
			if (headAreaMark_Array[0] === -1) {
				headAreaMark_Array[0] = i;
			} else {
				headAreaMark_Array[1] = i;
				break;
			}
		}
	}
	if (headAreaMark_Array[0] === -1 || headAreaMark_Array[1] === -1) {
		message_locator_service("HEAD AREA BOUNDRIES BUGGY OR NOT FOUND AT ALL...!");
		return false;
	} else {
		return headAreaMark_Array;
	}
}

function carriage_return_needed() {
	var os_Module = globalModule_Try('os');
	var windowsSpotter_RegExp = new RegExp("windows", "i");
	if (windowsSpotter_RegExp.exec(os_Module.type()) !== null) {
		return true;
	} else {
		return false;
	}
}

function end_of_line_clean_save(fileName, array, carriageReturn) {
	var carriageReturnString = "";
	if (carriageReturn) {
		carriageReturnString = "\r";
	}
	var fileSystem_Module = globalModule_Try('fs');
	var currentFileHandle = fileSystem_Module.openSync(fileName, 'w');

	var lineSpotter_RegExp = new RegExp("^([\\x20\\x09]*)(.*)\\x0d*$", "i");
	var initialLineResultArray = lineSpotter_RegExp.exec(array[0]);
	if (initialLineResultArray !== null) {
		if (initialLineResultArray[2]) {
			fileSystem_Module.writeSync(currentFileHandle, initialLineResultArray[1] + initialLineResultArray[2] +
			    carriageReturnString + "\n");
		}
	} else {
		message_locator_service("MISSED THE INITIAL LINE...!");
		return false;
	}
	for (var j = 1; j < (array.length - 1); j++) {
		var lineResultArray = lineSpotter_RegExp.exec(array[j]);
		if (lineResultArray !== null) {
			if (j === (array.length - 2)) {
				var nextToLast_ResultArray = lineSpotter_RegExp.exec(array[array.length - 1]);
				if (!nextToLast_ResultArray[2]) {
					fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2]);
				} else {
					fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2] + carriageReturnString +
					    "\n");
				}
			} else {
				fileSystem_Module.writeSync(currentFileHandle, lineResultArray[1] + lineResultArray[2] + carriageReturnString +
				    "\n");
			}
		} else {
			message_locator_service("MISSED A LINE...!");
			return false;
		}
	}
	var finalLineResultArray = lineSpotter_RegExp.exec(array[array.length - 1]);
	if (finalLineResultArray !== null) {
		if (finalLineResultArray[2]) {
			fileSystem_Module.writeSync(currentFileHandle, finalLineResultArray[1] + finalLineResultArray[2]);
		}
	} else {
		message_locator_service("MISSED THE FINAL LINE...!");
		return false;
	}
	fileSystem_Module.closeSync(currentFileHandle);
	return true;
}

function array_from_file_delete(entire_fileName) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(entire_fileName)) {
		var targetFile_LineArray = fileSystem_Module.readFileSync(entire_fileName, 'utf8', 'r').toString().split('\n');
		fileSystem_Module.unlinkSync(entire_fileName);
		return targetFile_LineArray;
	} else {
		message_locator_service("TARGET FILE DOES NOT EXIST...!");
		return false;
	}
}

function array_from_file(entire_fileName) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(entire_fileName)) {
		var targetFile_LineArray = fileSystem_Module.readFileSync(entire_fileName, 'utf8', 'r').toString().split('\n');
		return targetFile_LineArray;
	} else {
		message_locator_service("TARGET FILE DOES NOT EXIST...!");
		return false;
	}
}

// Switching html head area to minified targets...
function toMin(headStart, headEnd, carriageReturn, contentArray) {
	var changed = false;
	var hasMin_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)(?:\\.min)+(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	var carelessAboutMin_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	for (var i = (headStart + 1); i < headEnd; i++) {
		if (hasMin_RegExp.exec(contentArray[i]) === null) {
			var regExp_ResultArray = carelessAboutMin_RegExp.exec(contentArray[i]);
			if (regExp_ResultArray !== null) {
				contentArray[i] = regExp_ResultArray[1] + ".min" + regExp_ResultArray[2] + carriageReturn;
				if (!changed) {
					changed = true;
				}
			}
		}
	}
	if (changed) {
		return contentArray;
	} else {
		return false;
	}
}

// Switching html head area to regular targets...
function toRegular(headStart, headEnd, carriageReturn, contentArray) {
	var changed = false;
	var minSuspect_RegExp = new RegExp(
	    "^(.*(?:href|src)\\s*\\=\\s*(?:\"|\')?.+)\\.min(\\.(?:js|css)[\\x20\\t]*(?:\"|\')?[^\\x0d\\x0a]*)", "i");
	for (var i = (headStart + 1); i < headEnd; i++) {
		var regExp_ResultArray = minSuspect_RegExp.exec(contentArray[i]);
		if (regExp_ResultArray !== null) {
			contentArray[i] = regExp_ResultArray[1] + regExp_ResultArray[2] + carriageReturn;
			if (!changed) {
				changed = true;
			}
		}
	}
	if (changed) {
		return contentArray;
	} else {
		return false;
	}
}

function delete_writingArray_ToFile(fileName, array) {
	var fileSystem_Module = globalModule_Try('fs');
	if (fileSystem_Module.existsSync(fileName)) {
		fileSystem_Module.unlinkSync(fileName);
	}
	var inHouseFileHandle = fileSystem_Module.openSync(fileName, 'w');
	for (var i = 0; i < (array.length - 1); i++) {
		fileSystem_Module.writeSync(inHouseFileHandle, array[i] + "\n");
	}
	if (array[array.length - 1]) {
		fileSystem_Module.writeSync(inHouseFileHandle, array[array.length - 1]);
	}
	fileSystem_Module.closeSync(inHouseFileHandle);
}

module.exports = {
  casual__options__servant : function(options_object, option_request) {
	  var top_level_options_reference_object = {
	    action : [ 'switch', 'clean' ],
	    chattiness : [ 'true', 'false' ],
	    direction : [ 'min', 'regular' ],
	    file_source : [ 'wildcard', 'list' ],
	  };
	  for ( var item in options_object) {
		  if (item === option_request) {
			  console.log(item + ": \"" + options_object[item] + "\"");
			  if (true) {

			  } else {

			  }
		  } else {

		  }
	  }
  },

  add_on_options__servant : function(global_object) {
	  var noisy = true;
	  var global_options_object = global_object.data.options;
	  var global_add_on_options_object = {
		  chattiness : [ 'true', 'false' ]
	  };
	  if (global_options_object !== undefined) {
		  if (noisy) {
			  console.log(">>> Options section found... Doing further checking... <<<");
		  }
		  for ( var item in global_add_on_options_object) {
			  if (global_options_object.hasOwnProperty(item)) {
				  var contains_valid_value = false;
				  for (var i = 0; i < global_add_on_options_object[item].length; i++) {
					  if (global_add_on_options_object[item].includes(global_options_object[item])) {
						  contains_valid_value = true;
						  break;
					  }
				  }
				  if (!contains_valid_value) {
					  console.log("\"" + global_options_object[item] + "\" IS NOT A VALID OPTION WITH \"" + item + "\" ...!");
					  return false;
				  }
			  } else {
				  if (noisy) {
					  console.log("MISSING OBJECTS OPTIONS PROPERTY: \"" + item + "\" ...!");
				  }
				  return false;
			  }
		  }
		  return true;
	  } else {
		  console.log(">>> NO VALID OPTIONS SECTION FOUND...! <<<");
		  return false;
	  }
  },

  private_action_checker : function(global_object, reference_object, noisy) {
	  var global_options_object = global_object.data.options;
	  if (global_options_object !== undefined) {
		  if (noisy) {
			  console.log(">>> Options section found... Doing further checking... <<<");
		  }
		  for ( var item in reference_object) {
			  if (global_options_object.hasOwnProperty(item)) {
				  var contains_valid_value = false;
				  for (var i = 0; i < reference_object[item].length; i++) {
					  if (reference_object[item].includes(global_options_object[item])) {
						  contains_valid_value = true;
						  break;
					  }
				  }
				  if (!contains_valid_value) {
					  console.log("\"" + global_options_object[item] + "\" IS NOT A VALID OPTION WITH \"" + item + "\" ...!");
					  return false;
				  }
			  } else {
				  if (noisy) {
					  console.log("MISSING OBJECTS OPTIONS PROPERTY: \"" + item + "\" ...!");
				  }
				  return false;
			  }
		  }
		  return true;
	  } else {
		  console.log(">>> NO VALID OPTIONS SECTION FOUND...! <<<");
		  return false;
	  }
  },

  process_wildcard_input : function(source, directory) {
	  var wildcard_extractor_RegExp = new RegExp("^\\*(.+)$");
	  var result_array = wildcard_extractor_RegExp.exec(source);
	  var final_files_array = [];
	  if (result_array) {
		  var tail_string = result_array[1];
		  var prepared_tail = tail_string.replace(/\./ig, "\\.");
		  var wildcard_RegExp = new RegExp("^(.+" + prepared_tail + ")$", "i");
		  var fileSystem_Module = globalModule_Try('fs');
		  var raw_file_array = fileSystem_Module.readdirSync(directory);
		  var targets_file_array = [];
		  for (var i = 0; i < raw_file_array.length; i++) {
			  var single_file_result_array = wildcard_RegExp.exec(raw_file_array[i]);
			  if (single_file_result_array) {
				  final_files_array.push(directory + single_file_result_array[1]);
			  }
		  }
		  return final_files_array;
	  } else {
		  message_locator_service("NO VALID WILDCARD FOUND...!");
		  return false;
	  }
  },

  toggle_all_head_links : function(direction, file) {
	  var pointToMin = false;
	  if (direction === 'min') {
		  pointToMin = true;
	  }
	  var targetFile_LineArray = array_from_file(file);
	  if (targetFile_LineArray) {
		  var windowsNeeded_carriageReturn = "";
		  if (carriage_return_needed) {
			  windowsNeeded_carriageReturn = "\r";
		  }
		  var headStart = spot_the_head(targetFile_LineArray)[0];
		  var headEnd = spot_the_head(targetFile_LineArray)[1];

		  // Actual array manipulation...
		  if (pointToMin) {
			  targetFile_LineArray = toMin(headStart, headEnd, windowsNeeded_carriageReturn, targetFile_LineArray);
			  if (targetFile_LineArray) {
				  delete_writingArray_ToFile(file, targetFile_LineArray);
				  return true;
			  } else {
				  return true;
			  }
		  } else {
			  targetFile_LineArray = toRegular(headStart, headEnd, windowsNeeded_carriageReturn, targetFile_LineArray);
			  if (targetFile_LineArray) {
				  delete_writingArray_ToFile(file, targetFile_LineArray);
				  return true;
			  } else {
				  return true;
			  }
		  }
	  } else {
		  message_locator_service("FAILED TO GET VALID DATA ARRAY...!");
		  return false;
	  }
  },

  end_of_line_refresh : function(file) {
	  var targetFile_LineArray = array_from_file_delete(file);
	  if (targetFile_LineArray) {
		  return end_of_line_clean_save(file, targetFile_LineArray, carriage_return_needed());
	  } else {
		  message_locator_service("FAILED TO GET VALID DATA ARRAY...!");
		  return false;
	  }
  }
};
<|endoftext|>