<commit_before>var GM_prefRoot = new GM_PrefManager();

/**
 * Simple API on top of preferences for greasemonkey.
 * Construct an instance by passing the startPoint of a preferences subtree.
 * "greasemonkey." prefix is assumed.
 */
function GM_PrefManager(startPoint) {
  if (!startPoint) {
    startPoint = "";
  }

  startPoint = "greasemonkey." + startPoint;

  var pref = Components.classes["@mozilla.org/preferences-service;1"]
                       .getService(Components.interfaces.nsIPrefService)
                       .getBranch(startPoint);

  var observers = {};
  const nsISupportsString = Components.interfaces.nsISupportsString;

  /**
   * whether a preference exists
   */
  this.exists = function(prefName) {
    return pref.getPrefType(prefName) != 0;
  };

  /**
   * returns the named preference, or defaultValue if it does not exist
   */
  this.getValue = function(prefName, defaultValue) {
    var prefType = pref.getPrefType(prefName);

    // underlying preferences object throws an exception if pref doesn't exist
    if (prefType == pref.PREF_INVALID) {
      return defaultValue;
    }

    try {
      switch (prefType) {
        case pref.PREF_STRING:
          return pref.getComplexValue(prefName, nsISupportsString).data;
        case pref.PREF_BOOL:
          return pref.getBoolPref(prefName);
        case pref.PREF_INT:
          return pref.getIntPref(prefName);
      }
    } catch(ex) {
      return defaultValue != undefined ? defaultValue : null;
    }
    return null;
  };

  /**
   * sets the named preference to the specified value. values must be strings,
   * booleans, or integers.
   */
  this.setValue = function(prefName, value) {
    var prefType = typeof(value);

    switch (prefType) {
      case "string":
      case "boolean":
        break;
      case "number":
        if (value % 1 != 0) {
          // NOTE: Non localised strings
          throw new Error("Cannot set preference to non integral number");
        }
        break;
      default:
        throw new Error("Cannot set preference with datatype: " + prefType);
    }

    // underlying preferences object throws an exception if new pref has a
    // different type than old one. i think we should not do this, so delete
    // old pref first if this is the case.
    if (this.exists(prefName) && prefType != typeof(this.getValue(prefName))) {
      this.remove(prefName);
    }

    // set new value using correct method
    switch (prefType) {
      case "string":
        var str = Components.classes["@mozilla.org/supports-string;1"]
                            .createInstance(nsISupportsString);
        str.data = value;
        pref.setComplexValue(prefName, nsISupportsString, str);
        break;
      case "boolean":
        pref.setBoolPref(prefName, value);
        break;
      case "number":
        pref.setIntPref(prefName, Math.floor(value));
        break;
    }
  };

  /**
   * deletes the named preference or subtree
   */
  this.remove = function(prefName) {
    pref.deleteBranch(prefName);
  };

  /**
   * call a function whenever the named preference subtree changes
   */
  this.watch = function(prefName, watcher) {
    // construct an observer
    var observer = {
      observe:function(subject, topic, prefName) {
        watcher(prefName);
      }
    };

    // store the observer in case we need to remove it later
    observers[watcher] = observer;

    pref.QueryInterface(Components.interfaces.nsIPrefBranchInternal).
      addObserver(prefName, observer, false);
  };

  /**
   * stop watching
   */
  this.unwatch = function(prefName, watcher) {
    if (observers[watcher]) {
      pref.QueryInterface(Components.interfaces.nsIPrefBranchInternal).
        removeObserver(prefName, observers[watcher]);
    }
  };
};<commit_msg>Show a better error message when we fail due to invalid types in GM_setValue.<commit_after>var GM_prefRoot = new GM_PrefManager();

GM_PrefManager.MIN_INT_32 = (1 << 31);
GM_PrefManager.MAX_INT_32 = ~(1 << 31);

/**
 * Simple API on top of preferences for greasemonkey.
 * Construct an instance by passing the startPoint of a preferences subtree.
 * "greasemonkey." prefix is assumed.
 */
function GM_PrefManager(startPoint) {
  if (!startPoint) {
    startPoint = "";
  }

  startPoint = "greasemonkey." + startPoint;

  var pref = Components.classes["@mozilla.org/preferences-service;1"]
                       .getService(Components.interfaces.nsIPrefService)
                       .getBranch(startPoint);

  var observers = {};
  const nsISupportsString = Components.interfaces.nsISupportsString;

  /**
   * whether a preference exists
   */
  this.exists = function(prefName) {
    return pref.getPrefType(prefName) != 0;
  };

  /**
   * returns the named preference, or defaultValue if it does not exist
   */
  this.getValue = function(prefName, defaultValue) {
    var prefType = pref.getPrefType(prefName);

    // underlying preferences object throws an exception if pref doesn't exist
    if (prefType == pref.PREF_INVALID) {
      return defaultValue;
    }

    try {
      switch (prefType) {
        case pref.PREF_STRING:
          return pref.getComplexValue(prefName, nsISupportsString).data;
        case pref.PREF_BOOL:
          return pref.getBoolPref(prefName);
        case pref.PREF_INT:
          return pref.getIntPref(prefName);
      }
    } catch(ex) {
      return defaultValue != undefined ? defaultValue : null;
    }
    return null;
  };

  /**
   * sets the named preference to the specified value. values must be strings,
   * booleans, or integers.
   */
  this.setValue = function(prefName, value) {
    var prefType = typeof(value);
    var goodType = false;

    switch (prefType) {
      case "string":
      case "boolean":
        goodType = true;
        break;
      case "number":
        if (value % 1 == 0 &&
            value >= GM_PrefManager.MIN_INT_32 &&
            value <= GM_PrefManager.MAX_INT_32) {
          goodType = true;
        }
        break;
    }

    if (!goodType) {
      throw new Error("Unsupported type for GM_setValue. Supported types " +
                      "are: string, bool, and 32 bit integers.");
    }

    // underlying preferences object throws an exception if new pref has a
    // different type than old one. i think we should not do this, so delete
    // old pref first if this is the case.
    if (this.exists(prefName) && prefType != typeof(this.getValue(prefName))) {
      this.remove(prefName);
    }

    // set new value using correct method
    switch (prefType) {
      case "string":
        var str = Components.classes["@mozilla.org/supports-string;1"]
                            .createInstance(nsISupportsString);
        str.data = value;
        pref.setComplexValue(prefName, nsISupportsString, str);
        break;
      case "boolean":
        pref.setBoolPref(prefName, value);
        break;
      case "number":
        pref.setIntPref(prefName, Math.floor(value));
        break;
    }
  };

  /**
   * deletes the named preference or subtree
   */
  this.remove = function(prefName) {
    pref.deleteBranch(prefName);
  };

  /**
   * call a function whenever the named preference subtree changes
   */
  this.watch = function(prefName, watcher) {
    // construct an observer
    var observer = {
      observe:function(subject, topic, prefName) {
        watcher(prefName);
      }
    };

    // store the observer in case we need to remove it later
    observers[watcher] = observer;

    pref.QueryInterface(Components.interfaces.nsIPrefBranchInternal).
      addObserver(prefName, observer, false);
  };

  /**
   * stop watching
   */
  this.unwatch = function(prefName, watcher) {
    if (observers[watcher]) {
      pref.QueryInterface(Components.interfaces.nsIPrefBranchInternal).
        removeObserver(prefName, observers[watcher]);
    }
  };
};<|endoftext|>


<commit_before>const DEFAULT = require("./version.js");

class Request {
    constructor(event, context) {
        this.method = event.httpMethod;
        this.version = DEFAULT;
        if (event.queryStringParameters && (event.queryStringParameters.v || event.queryStringParameters.version)) {
            if (event.queryStringParameters.v) {
                this.version = event.queryStringParameters.v;
            } else {
                this.version = event.queryStringParameters.version;
            }
        }
        this.path = event.path;
        this.headers = event.headers;
        this.body = null;
        if (event.body) {
            this.body = JSON.parse(event.body);
        }
        this.parameters = {};
        if (event.queryStringParameters) {
            this.parameters = event.queryStringParameters;
        }
        this.user = null;
        if (event.requestContext && event.requestContext.authorizer && event.requestContext.authorizer.username) {
            this.user = { username: event.requestContext.authorizer.username, roles: null };
        }
        if (event.requestContext.requestId) {
            this.requestId = event.requestContext.requestId;
        }
        this._route = null;
        this.routes = null;
        this.originalEvent = event;
        this.context = context;
    }

    set route(route) {
        this._route = route;
        Object.assign(this.parameters, route.parameters);
        return this;
    }

    get route() {
        return this._route;
    }

}

module.exports = Request;<commit_msg>Add support for IAM user<commit_after>const DEFAULT = require("./version.js");

class Request {
    constructor(event, context) {
        this.method = event.httpMethod;
        this.version = DEFAULT;
        if (event.queryStringParameters && (event.queryStringParameters.v || event.queryStringParameters.version)) {
            if (event.queryStringParameters.v) {
                this.version = event.queryStringParameters.v;
            } else {
                this.version = event.queryStringParameters.version;
            }
        }
        this.path = event.path;
        this.headers = event.headers;
        this.body = null;
        if (event.body) {
            this.body = JSON.parse(event.body);
        }
        this.parameters = {};
        if (event.queryStringParameters) {
            this.parameters = event.queryStringParameters;
        }
        this.user = null;
        if (event.requestContext && event.requestContext.authorizer && event.requestContext.authorizer.username) {
            this.user = { username: event.requestContext.authorizer.username, roles: null };
        }
        if (event.requestContext.requestId) {
            this.requestId = event.requestContext.requestId;
        }
        if (event.requestContext && event.requestContext.identity && event.requestContext.identity.caller) {
            if (this.user === null) {
                this.user = {};
            }
            this.user.caller = event.requestContext.identity.caller;
        }
        if (event.requestContext && event.requestContext.identity && event.requestContext.identity.userArn) {
            if (this.user === null) {
                this.user = {};
            }
            this.user.userArn = event.requestContext.identity.userArn;
        }
        if (event.requestContext && event.requestContext.identity && event.requestContext.identity.user) {
            if (this.user === null) {
                this.user = {};
            }
            this.user.user = event.requestContext.identity.user;
        }
        this._route = null;
        this.routes = null;
        this.originalEvent = event;
        this.context = context;
    }

    set route(route) {
        this._route = route;
        Object.assign(this.parameters, route.parameters);
        return this;
    }

    get route() {
        return this._route;
    }

}

module.exports = Request;<|endoftext|>


<commit_before>'use strict';

const fs = require('fs-extra');
const path = require('path');
const periodicjs = require('periodicjs');
const Promisie = require('promisie');

/**
 * exports data from a given core data database model
 *
 * @param {string} core_data_name
 * @returns {Promise} contents of the core data model seed
 */
function exportCoreData(core_data_name) {
  return new Promise((resolve, reject) => {
    try {
      periodicjs.datas.get(core_data_name).query()
        .then(data => {
          resolve({
            [ core_data_name ]: data,
          });
        })
        .catch(reject);
    } catch (e) {
      reject(e);
    }
  });
}

/**
 * exports all data from periodic into a seed file
 *
 * @param {string} filepath
 * @returns {Promise} resolved value from each export from exportCoreData
 */
function exportData(filepath) {
  return new Promise((resolve, reject) => {
    try {
      const excluded_data = periodicjs.settings.extensions['periodicjs.ext.dbseed'].export.ignore_core_datas;
      const core_datas = Array.from(periodicjs.datas.keys()).filter(datum => excluded_data.indexOf(datum) === -1);
      fs.ensureFile(filepath)
        .then(() => {
          return Promisie.map(core_datas, 5, exportCoreData);
        })
        .then(datas => {
          resolve(fs.outputJSON(filepath, datas));
        })
        .catch(reject);
    } catch (e) {
      reject(e);
    }
  });
}

module.exports = {
  exportCoreData,
  // exportCoreDatabase,
  exportData,
};<commit_msg>export seed working with partitions<commit_after>'use strict';

const Promisie = require('promisie');
const fs = Promisie.promisifyAll(require('fs-extra'));
const path = require('path');
const periodicjs = require('periodicjs');
const Transform = require('stream').Transform;

/**
 * exports data from a given core data database model
 *
 * @param {string} core_data_name
 * @returns {Promise} contents of the core data model seed
 */
function handleWriteStream (fd) {
  let isFirst = true;
  let transform = new Transform({
    objectMode: true,
    transform: function (data, enc, next) {
      try {
        if (isFirst) {
          isFirst = false;
          this.push('[');
        }
        this.push((data && typeof data === 'object') ? JSON.stringify(data) : data);
        next();
      } catch (e) {
        next(e);
      }
    }
  });
  transform.pipe(fd);
  return transform;
}

function handleReadStream (core_data_name, writeStream, fd) {
  let firstData = true;
  return function (readStream) {
    let count = 0;
    return new Promisie((resolve, reject) => {
      try {
        writeStream.write(`{"${ core_data_name }": [`);
        writeStream.once('error', reject);
        readStream.on('data', data => {
          count++;
          if (firstData) {
            firstData = false;
            writeStream.write(data);
          } else {
            writeStream.write(',');
            writeStream.write(data);
          }
        })
          .on('error', reject)
          .on('end', () => {
            writeStream.write(']');
            resolve([writeStream, fd, count]);
          });
      } catch (e) {
        reject(e);
      }
    });
  }
}

function handleWriteEnd (transform, fd) {
  transform.end('}]');
  return new Promisie((resolve, reject) => {
    fd.on('finish', () => resolve())
      .on('error', reject);
  });
}

function exportCoreData (filepath, split_count) {
  return function (core_data_name) {
    let data_count = 0;
    let file_index = 0;
    return Promisie.doWhilst(() => {
      let fd = fs.createWriteStream(path.join(path.dirname(filepath), `${ path.basename(filepath, '.json') }_${ core_data_name }(${ file_index }).json`));
      let writeStream = handleWriteStream(fd);
      return periodicjs.datas.get(core_data_name).stream({
        limit: (typeof split_count === 'number') ? split_count : Infinity,
        skip: data_count
      })
        .then(handleReadStream(core_data_name, writeStream, fd))
        .then(result => {
          let [transform, fd, count] = result;
          data_count += count;
          file_index++;
          return handleWriteEnd(transform, fd)
            .then(() => count)
            .catch(e => Promisie.reject(e));
        })
        .catch(e => Promisie.reject(e));
    }, result => (typeof split_count === 'number' && split_count > 0 && result === split_count));
  }
}

/**
 * exports all data from periodic into a seed file
 *
 * @param {string} filepath
 * @returns {Promise} resolved value from each export from exportCoreData
 */
function exportData (filepath) {
  try {
    const excluded_data = periodicjs.settings.extensions['periodicjs.ext.dbseed'].export.ignore_core_datas;
    const split_count = periodicjs.settings.extensions['periodicjs.ext.dbseed'].export.split_count;
    const core_datas = Array.from(periodicjs.datas.keys()).filter(datum => excluded_data.indexOf(datum) === -1);
    return Promisie.map(core_datas, 5, exportCoreData(filepath, split_count));
  } catch (e) {
    return Promisie.reject(e);
  }
}

module.exports = {
  exportCoreData,
  // exportCoreDatabase,
  exportData,
};<|endoftext|>


<commit_before>import _ from "lodash";
import PropTypes from "prop-types";
import React, { Component } from "react";

import Button from "@material-ui/core/Button";
import SelectSearch from "react-select-search";

class EpisodeIDSelector extends Component {
    constructor(props) {
        super(props);

        this.state = {
            currentShowID: 0,
            currentSeasonID: 0,
            currentEpisodeID: 0,
            episodes: [],
            seasons: [],
            shows: [],
        };
    }

    componentWillMount() {
        this._getShows();
    }

    _getShows() {
        const { callAPI } = this.props;

        callAPI("shows.shows.get", {}, this._showsReceived.bind(this), false);
    }

    _showsReceived(shows) {
        this.setState({
            currentSeasonID: 0,
            currentEpisodeID: 0,
            shows,
            seasons: [],
            episodes: [],
        });
    }

    _getSeasons(showID) {
        const { callAPI } = this.props;

        this.setState({
            currentEpisodeID: 0,
            currentSeasonID: 0,
            currentShowID: parseInt(showID),
            seasons: [],
            episodes: [],
        });

        const options = {
            show_id: showID,
        };
        callAPI(
            "shows.seasons.get",
            options,
            this._seasonsReceived.bind(this),
            false
        );
    }

    _seasonsReceived(seasons) {
        this.setState({
            seasons,
        });
    }

    _getEpisodes(seasonID) {
        const { callAPI } = this.props;

        this.setState({
            currentSeasonID: parseInt(seasonID),
            currentEpisodeID: 0,
            episodes: [],
        });

        const options = {
            show_id: this.state.currentShowID,
            season_id: seasonID,
        };
        callAPI(
            "shows.episodes.get",
            options,
            this._episodesReceived.bind(this),
            false
        );
    }

    _episodesReceived(episodes) {
        this.setState({
            episodes,
        });
    }

    _handleSelectEpisode(episodeID) {
        this.setState({
            currentEpisodeID: parseInt(episodeID),
        });
    }

    _buildSelect(
        items,
        titleKey,
        onChange,
        defaultValue,
        prefix = "",
        searchable = false
    ) {
        let options = [];

        items.forEach((item) => {
            const optionValue = prefix + item[titleKey];
            options.push({ value: item.id.toString(), name: optionValue });
        });

        return (
            <SelectSearch
                className="select-search"
                options={options}
                placeholder="Select..."
                value={defaultValue.toString()}
                onChange={onChange}
                search={searchable}
            >
                {options}
            </SelectSearch>
        );
    }

    _handleClickIDButton() {
        const { onIDEpisode } = this.props;
        const { currentShowID, currentSeasonID, currentEpisodeID } = this.state;

        const episodeInfo = {
            currentShowID,
            currentSeasonID,
            currentEpisodeID,
        };

        onIDEpisode(episodeInfo);
    }

    render() {
        const {
            currentShowID,
            currentSeasonID,
            currentEpisodeID,
            episodes,
            seasons,
            shows,
        } = this.state;

        const showSelector = this._buildSelect(
            shows,
            "title",
            this._getSeasons.bind(this),
            currentShowID,
            "",
            true
        );
        let seasonsSelector = "Select a show...";
        if (currentShowID > 0) {
            seasonsSelector = this._buildSelect(
                seasons,
                "season_number",
                this._getEpisodes.bind(this),
                currentSeasonID,
                "Season ",
                true
            );
        }
        let episodesSelector = "Select a season...";
        if (currentSeasonID > 0) {
            episodesSelector = this._buildSelect(
                episodes,
                "episode_number",
                this._handleSelectEpisode.bind(this),
                currentEpisodeID,
                "Episode ",
                true
            );
        }

        let buttonDisabled = true;
        if (currentShowID > 0 && currentSeasonID > 0 && currentEpisodeID > 0) {
            buttonDisabled = false;
        }
        return (

{showSelector}

{seasonsSelector}

{episodesSelector}

                    <Button
                        variant="contained"
                        color="primary"
                        onClick={this._handleClickIDButton.bind(this)}
                        disabled={buttonDisabled}
                    >
                        ID Episode
                    </Button>

        );
    }
}

EpisodeIDSelector.propTypes = {
    callAPI: PropTypes.func.isRequired,
    onIDEpisode: PropTypes.func.isRequired,
};

export default EpisodeIDSelector;
<commit_msg>Added step name to placeholder<commit_after>import _ from "lodash";
import PropTypes from "prop-types";
import React, { Component } from "react";

import Button from "@material-ui/core/Button";
import SelectSearch from "react-select-search";

class EpisodeIDSelector extends Component {
    constructor(props) {
        super(props);

        this.state = {
            currentShowID: 0,
            currentSeasonID: 0,
            currentEpisodeID: 0,
            episodes: [],
            seasons: [],
            shows: [],
        };
    }

    componentWillMount() {
        this._getShows();
    }

    _getShows() {
        const { callAPI } = this.props;

        callAPI("shows.shows.get", {}, this._showsReceived.bind(this), false);
    }

    _showsReceived(shows) {
        this.setState({
            currentSeasonID: 0,
            currentEpisodeID: 0,
            shows,
            seasons: [],
            episodes: [],
        });
    }

    _getSeasons(showID) {
        const { callAPI } = this.props;

        this.setState({
            currentEpisodeID: 0,
            currentSeasonID: 0,
            currentShowID: parseInt(showID),
            seasons: [],
            episodes: [],
        });

        const options = {
            show_id: showID,
        };
        callAPI(
            "shows.seasons.get",
            options,
            this._seasonsReceived.bind(this),
            false
        );
    }

    _seasonsReceived(seasons) {
        this.setState({
            seasons,
        });
    }

    _getEpisodes(seasonID) {
        const { callAPI } = this.props;

        this.setState({
            currentSeasonID: parseInt(seasonID),
            currentEpisodeID: 0,
            episodes: [],
        });

        const options = {
            show_id: this.state.currentShowID,
            season_id: seasonID,
        };
        callAPI(
            "shows.episodes.get",
            options,
            this._episodesReceived.bind(this),
            false
        );
    }

    _episodesReceived(episodes) {
        this.setState({
            episodes,
        });
    }

    _handleSelectEpisode(episodeID) {
        this.setState({
            currentEpisodeID: parseInt(episodeID),
        });
    }

    _buildSelect(
        items,
        titleKey,
        onChange,
        defaultValue,
        prefix = "",
        searchable = false,
        placeholder = ""
    ) {
        let options = [];

        items.forEach((item) => {
            const optionValue = prefix + item[titleKey];
            options.push({ value: item.id.toString(), name: optionValue });
        });

        return (
            <SelectSearch
                className="select-search"
                options={options}
                placeholder={"Select " + placeholder + "..."}
                value={defaultValue.toString()}
                onChange={onChange}
                search={searchable}
            >
                {options}
            </SelectSearch>
        );
    }

    _handleClickIDButton() {
        const { onIDEpisode } = this.props;
        const { currentShowID, currentSeasonID, currentEpisodeID } = this.state;

        const episodeInfo = {
            currentShowID,
            currentSeasonID,
            currentEpisodeID,
        };

        onIDEpisode(episodeInfo);
    }

    render() {
        const {
            currentShowID,
            currentSeasonID,
            currentEpisodeID,
            episodes,
            seasons,
            shows,
        } = this.state;

        const showSelector = this._buildSelect(
            shows,
            "title",
            this._getSeasons.bind(this),
            currentShowID,
            "",
            true,
            "Show"
        );
        let seasonsSelector = "Select a show...";
        if (currentShowID > 0) {
            seasonsSelector = this._buildSelect(
                seasons,
                "season_number",
                this._getEpisodes.bind(this),
                currentSeasonID,
                "Season ",
                true,
                "Season"
            );
        }
        let episodesSelector = "Select a season...";
        if (currentSeasonID > 0) {
            episodesSelector = this._buildSelect(
                episodes,
                "episode_number",
                this._handleSelectEpisode.bind(this),
                currentEpisodeID,
                "Episode ",
                true,
                "Episode"
            );
        }

        let buttonDisabled = true;
        if (currentShowID > 0 && currentSeasonID > 0 && currentEpisodeID > 0) {
            buttonDisabled = false;
        }
        return (

{showSelector}

{seasonsSelector}

{episodesSelector}

                    <Button
                        variant="contained"
                        color="primary"
                        onClick={this._handleClickIDButton.bind(this)}
                        disabled={buttonDisabled}
                    >
                        ID Episode
                    </Button>

        );
    }
}

EpisodeIDSelector.propTypes = {
    callAPI: PropTypes.func.isRequired,
    onIDEpisode: PropTypes.func.isRequired,
};

export default EpisodeIDSelector;
<|endoftext|>


<commit_before>let path = require('path')
let logger = require('morgan')
let cookieParser = require('cookie-parser')
let bodyParser = require('body-parser')
var favicon = require('serve-favicon')

function middlewares (express, app, io) {
  app.use((req, res, next) => {
    res.io = io
    next()
  })

  app.use(require('node-sass-middleware')({
    src: path.join(path.dirname(require.main.filename), 'public'),
    dest: path.join(path.dirname(require.main.filename), 'public'),
    indentedSyntax: false,
    sourceMap: true,
    outputStyle: 'compressed',
    debug: true
  }))
  app.use(logger('dev'))
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({
    extended: false
  }))
  app.use(cookieParser())
  app.use(express.static(path.join(path.dirname(require.main.filename), '/public')))
}

module.exports = middlewares
<commit_msg>Suppression d'une dependance inutile<commit_after>let path = require('path')
let logger = require('morgan')
let cookieParser = require('cookie-parser')
let bodyParser = require('body-parser')

function middlewares (express, app, io) {
  app.use((req, res, next) => {
    res.io = io
    next()
  })

  app.use(require('node-sass-middleware')({
    src: path.join(path.dirname(require.main.filename), 'public'),
    dest: path.join(path.dirname(require.main.filename), 'public'),
    indentedSyntax: false,
    sourceMap: true,
    outputStyle: 'compressed',
    debug: true
  }))
  app.use(logger('dev'))
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({
    extended: false
  }))
  app.use(cookieParser())
  app.use(express.static(path.join(path.dirname(require.main.filename), '/public')))
}

module.exports = middlewares
<|endoftext|>


<commit_before>/*******************************************************************************
 * (C) Copyright 2016 Jerome Comte and Dorian Cransac
 *
 * This file is part of STEP
 *
 * STEP 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.
 *
 * STEP 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 STEP.  If not, see <http://www.gnu.org/licenses/>.
 *******************************************************************************/
angular.module('plans',['tables','step','screenConfigurationControllers'])

.run(function(ViewRegistry, EntityRegistry) {
  ViewRegistry.registerView('plans','partials/plans/plans.html');
  EntityRegistry.registerEntity('Plan', 'plans', 'plans', 'rest/plans/', 'rest/plans/', 'st-table', '/partials/plans/planSelectionTable.html');
})

.factory('PlanTypeRegistry', function() {

  var api = {};

  var registry = {};

  api.register = function(type, label, editor) {
    registry[type] = {
      editor: editor,
      label: label,
      type: type
    };
  };

  api.getEditorView = function(type){
    return registry[type].editor;
  };

  api.getPlanTypes = function() {
    return _.values(registry);
  }

  api.getPlanType = function(typeName) {
    return registry[typeName];
  }

  return api;
})

.controller('PlansCtrl', function($rootScope, $scope, stateStorage) {
  stateStorage.push($scope, 'plans', {});

  $scope.$watch('$state',function() {
    if($scope.$state!=null) {
      $scope.selectView = $scope.$state
    }
  });
})

.controller('PlanListCtrl', function($rootScope, $scope, $http, $location, $uibModal, stateStorage, ExportService, Dialogs, PlanDialogs, AuthService) {
    stateStorage.push($scope, 'list', {});
    $scope.authService = AuthService;

    $scope.tableHandle = {};

    function reload() {
      $scope.tableHandle.reload();
    }

    $scope.addPlan = function() {
      PlanDialogs.createPlan(function(plan) {
        reload();
      });
    }

    $scope.editPlan = function(id) {
      $location.path('/root/plans/editor/' + id);
    }

    $scope.executePlan = function(id) {
      $location.path('/root/repository').search({repositoryId:'local',planid:id});
    }

    $scope.copyPlan = function(id) {
      $rootScope.clipboard = {object:"plan",id:id};
    }

    $scope.pastePlan = function() {
      if($rootScope.clipboard && $rootScope.clipboard.object=="plan") {
        $http.get("rest/plans/"+$rootScope.clipboard.id+"/clone").then(function(response) {
          var clone = response.data;
          clone.attributes.name = clone.attributes.name + "_Copy"
          $http.post("rest/plans", clone).then(function(response) {
            reload();
          })
        });
      }
    }

    $scope.deletePlan = function(id) {
      Dialogs.showDeleteWarning().then(function() {
        $http.delete("rest/plans/"+id).then(function() {
          reload();
        });
      })
    }

    $scope.importPlans = function() {
      var modalInstance = $uibModal.open({
        backdrop: 'static',
        templateUrl: 'partials/plans/importPlansDialog.html',
        controller: 'importPlansModalCtrl',
        resolve: {}
      });

      modalInstance.result.then(function () {
        reload();
      });
    }

    $scope.exportPlans = function() {
      ExportService.get("rest/export/plans")
    }

  })

.factory('PlanDialogs', function ($uibModal, $http, Dialogs) {

  var dialogs = {};

  dialogs.createPlan = function(callback) {
    var modalInstance = $uibModal.open({
      backdrop: 'static',
      templateUrl: 'partials/plans/createPlanDialog.html',
      controller: 'createPlanCtrl',
      resolve: {}
    });

    modalInstance.result.then(function(plan) {
      if(callback){callback(plan)};
    })
  }

  dialogs.selectPlan = function(callback) {
    Dialogs.selectEntityOfType('plans', true).then(function(result) {
      var id = result.item;
      $http.get('rest/plans/'+id).then(function(response) {
        var plan = response.data;
        if(callback){callback(plan)};
      })
    });
  }

  return dialogs;
})

.controller('createPlanCtrl', function ($scope, $uibModalInstance, $location, $http, AuthService, ScreenTemplates, PlanTypeRegistry) {
  $scope.AuthService = AuthService;

  $scope.template = 'Sequence';
  $scope.plan = {attributes:{}};

  $scope.planTypes = PlanTypeRegistry.getPlanTypes();
  $scope.planType = PlanTypeRegistry.getPlanType('step.core.plans.Plan');

  $http.get("rest/controller/artefact/types").then(function(response){
    $scope.artefactTypes = response.data;
  })

  $scope.save = function (editAfterSave) {
    $http.get("rest/plans?type="+$scope.planType.type+'&template='+$scope.template).then(function(response){
      var createdPlan = response.data;
      createdPlan.attributes = $scope.plan.attributes;
      $http.post("rest/plans", createdPlan).then(function(response) {
        $uibModalInstance.close(response.data);
        if(editAfterSave) {
          $location.path('/root/plans/editor/' + createdPlan.id);
        }
      })
    })
  }

  $scope.cancel = function () {
    $uibModalInstance.dismiss('cancel');
  };
})

.controller('importPlansModalCtrl', function ($scope, $http, $uibModalInstance, Upload, Dialogs) {
  $scope.resourcePath;

  $scope.save = function() {
    if($scope.resourcePath) {
      $http({url:"rest/import/artefact",method:"POST",params:{path:$scope.resourcePath}}).then(function(response) {
        $uibModalInstance.close(response.data);
      })
    } else {
      Dialogs.showErrorMsg("Upload not completed.");
    }
  }

  $scope.cancel = function () {
    $uibModalInstance.dismiss('cancel');
  };
})
<commit_msg>SED-279 Setting attributes.name of root artefact of plan<commit_after>/*******************************************************************************
 * (C) Copyright 2016 Jerome Comte and Dorian Cransac
 *
 * This file is part of STEP
 *
 * STEP 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.
 *
 * STEP 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 STEP.  If not, see <http://www.gnu.org/licenses/>.
 *******************************************************************************/
angular.module('plans',['tables','step','screenConfigurationControllers'])

.run(function(ViewRegistry, EntityRegistry) {
  ViewRegistry.registerView('plans','partials/plans/plans.html');
  EntityRegistry.registerEntity('Plan', 'plans', 'plans', 'rest/plans/', 'rest/plans/', 'st-table', '/partials/plans/planSelectionTable.html');
})

.factory('PlanTypeRegistry', function() {

  var api = {};

  var registry = {};

  api.register = function(type, label, editor) {
    registry[type] = {
      editor: editor,
      label: label,
      type: type
    };
  };

  api.getEditorView = function(type){
    return registry[type].editor;
  };

  api.getPlanTypes = function() {
    return _.values(registry);
  }

  api.getPlanType = function(typeName) {
    return registry[typeName];
  }

  return api;
})

.controller('PlansCtrl', function($rootScope, $scope, stateStorage) {
  stateStorage.push($scope, 'plans', {});

  $scope.$watch('$state',function() {
    if($scope.$state!=null) {
      $scope.selectView = $scope.$state
    }
  });
})

.controller('PlanListCtrl', function($rootScope, $scope, $http, $location, $uibModal, stateStorage, ExportService, Dialogs, PlanDialogs, AuthService) {
    stateStorage.push($scope, 'list', {});
    $scope.authService = AuthService;

    $scope.tableHandle = {};

    function reload() {
      $scope.tableHandle.reload();
    }

    $scope.addPlan = function() {
      PlanDialogs.createPlan(function(plan) {
        reload();
      });
    }

    $scope.editPlan = function(id) {
      $location.path('/root/plans/editor/' + id);
    }

    $scope.executePlan = function(id) {
      $location.path('/root/repository').search({repositoryId:'local',planid:id});
    }

    $scope.copyPlan = function(id) {
      $rootScope.clipboard = {object:"plan",id:id};
    }

    $scope.pastePlan = function() {
      if($rootScope.clipboard && $rootScope.clipboard.object=="plan") {
        $http.get("rest/plans/"+$rootScope.clipboard.id+"/clone").then(function(response) {
          var clone = response.data;
          clone.attributes.name = clone.attributes.name + "_Copy"
          $http.post("rest/plans", clone).then(function(response) {
            reload();
          })
        });
      }
    }

    $scope.deletePlan = function(id) {
      Dialogs.showDeleteWarning().then(function() {
        $http.delete("rest/plans/"+id).then(function() {
          reload();
        });
      })
    }

    $scope.importPlans = function() {
      var modalInstance = $uibModal.open({
        backdrop: 'static',
        templateUrl: 'partials/plans/importPlansDialog.html',
        controller: 'importPlansModalCtrl',
        resolve: {}
      });

      modalInstance.result.then(function () {
        reload();
      });
    }

    $scope.exportPlans = function() {
      ExportService.get("rest/export/plans")
    }

  })

.factory('PlanDialogs', function ($uibModal, $http, Dialogs) {

  var dialogs = {};

  dialogs.createPlan = function(callback) {
    var modalInstance = $uibModal.open({
      backdrop: 'static',
      templateUrl: 'partials/plans/createPlanDialog.html',
      controller: 'createPlanCtrl',
      resolve: {}
    });

    modalInstance.result.then(function(plan) {
      if(callback){callback(plan)};
    })
  }

  dialogs.selectPlan = function(callback) {
    Dialogs.selectEntityOfType('plans', true).then(function(result) {
      var id = result.item;
      $http.get('rest/plans/'+id).then(function(response) {
        var plan = response.data;
        if(callback){callback(plan)};
      })
    });
  }

  return dialogs;
})

.controller('createPlanCtrl', function ($scope, $uibModalInstance, $location, $http, AuthService, ScreenTemplates, PlanTypeRegistry) {
  $scope.AuthService = AuthService;

  $scope.template = 'Sequence';
  $scope.plan = {attributes:{}};

  $scope.planTypes = PlanTypeRegistry.getPlanTypes();
  $scope.planType = PlanTypeRegistry.getPlanType('step.core.plans.Plan');

  $http.get("rest/controller/artefact/types").then(function(response){
    $scope.artefactTypes = response.data;
  })

  $scope.save = function (editAfterSave) {
    $http.get("rest/plans?type="+$scope.planType.type+'&template='+$scope.template).then(function(response){
      var createdPlan = response.data;
      createdPlan.attributes = $scope.plan.attributes;
      if(createdPlan.root) {
        createdPlan.root.attributes = createdPlan.attributes;
      }
      $http.post("rest/plans", createdPlan).then(function(response) {
        $uibModalInstance.close(response.data);
        if(editAfterSave) {
          $location.path('/root/plans/editor/' + createdPlan.id);
        }
      })
    })
  }

  $scope.cancel = function () {
    $uibModalInstance.dismiss('cancel');
  };
})

.controller('importPlansModalCtrl', function ($scope, $http, $uibModalInstance, Upload, Dialogs) {
  $scope.resourcePath;

  $scope.save = function() {
    if($scope.resourcePath) {
      $http({url:"rest/import/artefact",method:"POST",params:{path:$scope.resourcePath}}).then(function(response) {
        $uibModalInstance.close(response.data);
      })
    } else {
      Dialogs.showErrorMsg("Upload not completed.");
    }
  }

  $scope.cancel = function () {
    $uibModalInstance.dismiss('cancel');
  };
})
<|endoftext|>


<commit_before>/* jshint browser: true */
/* jshint unused: false */
/* global Backbone, frontendConfig, window, ArangoQuery, $, arangoHelper */
(function () {
  'use strict';

  window.ArangoQueries = Backbone.Collection.extend({
    initialize: function (models, options) {
      var self = this;

      $.ajax('whoAmI?_=' + Date.now(), {async: true}).done(
        function (data) {
          if (this.activeUser === false || this.activeUser === null) {
            self.activeUser = 'root';
          } else {
            self.activeUser = data.user;
          }
        }
      );
    },

    fetch: function (options) {
      if (window.App.currentUser && window.App.currentDB.get('name') !== '_system') {
        this.url = frontendConfig.basePath + '/_api/user/' + encodeURIComponent(window.App.currentUser);
      }
      return Backbone.Collection.prototype.fetch.call(this, options);
    },

    url: arangoHelper.databaseUrl('/_api/user/'),

    model: ArangoQuery,

    activeUser: null,

    parse: function (response) {
      var self = this; var toReturn;
      if (this.activeUser === false || this.activeUser === null) {
        this.activeUser = 'root';
      }

      if (response.user === self.activeUser) {
        try {
          if (response.extra.queries) {
            toReturn = response.extra.queries;
          }
        } catch (e) {}
      }

      return toReturn;
    },

    saveCollectionQueries: function (callback) {
      if (this.activeUser === false || this.activeUser === null) {
        this.activeUser = 'root';
      }

      var queries = [];

      this.each(function (query) {
        queries.push({
          value: query.attributes.value,
          parameter: query.attributes.parameter,
          name: query.attributes.name
        });
      });

      // save current collection
      $.ajax({
        cache: false,
        type: 'PATCH',
        url: arangoHelper.databaseUrl('/_api/user/' + encodeURIComponent(this.activeUser)),
        data: JSON.stringify({
          extra: {
            queries: queries
          }
        }),
        contentType: 'application/json',
        processData: false,
        success: function (data) {
          callback(false, data);
        },
        error: function () {
          callback(true);
        }
      });
    },

    saveImportQueries: function (file, callback) {
      if (this.activeUser === 0) {
        return false;
      }

      window.progressView.show('Fetching documents...');
      $.ajax({
        cache: false,
        type: 'POST',
        url: 'query/upload/' + encodeURIComponent(this.activeUser),
        data: file,
        contentType: 'application/json',
        processData: false,
        success: function () {
          window.progressView.hide();
          arangoHelper.arangoNotification('Queries successfully imported.');
          callback();
        },
        error: function () {
          window.progressView.hide();
          arangoHelper.arangoError('Query error', 'queries could not be imported');
        }
      });
    }

  });
}());
<commit_msg>fixed issue #2764 - adapted ui to api changes (#2836)<commit_after>/* jshint browser: true */
/* jshint unused: false */
/* global Backbone, _, frontendConfig, window, ArangoQuery, $, arangoHelper */
(function () {
  'use strict';

  window.ArangoQueries = Backbone.Collection.extend({
    initialize: function (models, options) {
      var self = this;

      $.ajax('whoAmI?_=' + Date.now(), {async: true}).done(
        function (data) {
          if (this.activeUser === false || this.activeUser === null) {
            self.activeUser = 'root';
          } else {
            self.activeUser = data.user;
          }
        }
      );
    },

    fetch: function (options) {
      if (window.App.currentUser && window.App.currentDB.get('name') !== '_system') {
        this.url = frontendConfig.basePath + '/_api/user/' + encodeURIComponent(window.App.currentUser);
      }
      return Backbone.Collection.prototype.fetch.call(this, options);
    },

    url: arangoHelper.databaseUrl('/_api/user/'),

    model: ArangoQuery,

    activeUser: null,

    parse: function (response) {
      var self = this; var toReturn;
      if (this.activeUser === false || this.activeUser === null) {
        this.activeUser = 'root';
      }
      console.log(response);

      if (response.user === self.activeUser) {
        try {
          if (response.extra.queries) {
            toReturn = response.extra.queries;
          }
        } catch (e) {}
      } else {
        if (response.result && response.result instanceof Array) {
          _.each(response.result, function (userobj) {
            if (userobj.user === self.activeUser) {
              toReturn = userobj.extra.queries;
            }
          });
        }
      }

      return toReturn;
    },

    saveCollectionQueries: function (callback) {
      if (this.activeUser === false || this.activeUser === null) {
        this.activeUser = 'root';
      }

      var queries = [];

      this.each(function (query) {
        queries.push({
          value: query.attributes.value,
          parameter: query.attributes.parameter,
          name: query.attributes.name
        });
      });

      // save current collection
      $.ajax({
        cache: false,
        type: 'PATCH',
        url: arangoHelper.databaseUrl('/_api/user/' + encodeURIComponent(this.activeUser)),
        data: JSON.stringify({
          extra: {
            queries: queries
          }
        }),
        contentType: 'application/json',
        processData: false,
        success: function (data) {
          callback(false, data);
        },
        error: function () {
          callback(true);
        }
      });
    },

    saveImportQueries: function (file, callback) {
      if (this.activeUser === 0) {
        return false;
      }

      window.progressView.show('Fetching documents...');
      $.ajax({
        cache: false,
        type: 'POST',
        url: 'query/upload/' + encodeURIComponent(this.activeUser),
        data: file,
        contentType: 'application/json',
        processData: false,
        success: function () {
          window.progressView.hide();
          arangoHelper.arangoNotification('Queries successfully imported.');
          callback();
        },
        error: function () {
          window.progressView.hide();
          arangoHelper.arangoError('Query error', 'queries could not be imported');
        }
      });
    }

  });
}());
<|endoftext|>


<commit_before>'use strict';

/**
 * @namespace
 */

var File = new Class( function ( file ) {

	this.private.fileInfo = file;
} );

File.prototype.private.resolvePath = function ( filePath ) {

	var isAbsolute = ( new java.io.File( filePath ) ).isAbsolute();

	var path = filePath;

	if ( !isAbsolute ) {
		path = java.nio.file.Paths.get( this.private.fileInfo.__dirname, filePath ).toString();
	}

	return path;
};

/**
 * Allows you to read and return the value of a file.
 * @implements File
 * @param {String} path - Specify a target text file to read.
 * @return {String}
 * @example
 * var data = File.read( './text.txt' );
 */

File.prototype.read = function ( filePath ) {

	var path = this.private.resolvePath( filePath );

	var contents = [];
	var line     = undefined;

	var file = new java.io.File( path );

	if ( file.exists() ) {

		var fileReader = new java.io.FileReader( path );

		var bufferReader = new java.io.BufferedReader( fileReader );

		while ( ( line = bufferReader.readLine() ) !== null ) {
			contents.push( line );
		}

		bufferReader.close();
		fileReader.close();

		return contents.join( '\n' );

	} else {
		console.log( '[ERROR]'.orange() + ' File not found:\n' + path + ':' + '\n' );
	}
};

/**
 * Allows you to write data to a file.
 * @implements File
 * @param {String} path - Specify a target file path.
 * @param {String} [data] - The data to be written to the file.
 * @example
 * File.write( './text.txt' );
 * File.write( './text.txt', 'yay' );
 */

File.prototype.write = function ( filePath, data ) {

	var path = this.private.resolvePath( filePath );

	var FileWriter = Java.type( 'java.io.FileWriter' );

	var file = new FileWriter( path );

	file.write( data || '' );
	file.close();
};

/**
 * Alias for File.write().
 * @implements File
 * @param {String} path - Specify a target file path.
 * @param {String} [data] - The data to be written to the file.
 * @example
 * File.create( './text.txt' );
 * File.create( './text.txt', 'yay' );
 */

File.prototype.create = function ( filePath, data ) {

	this.write( filePath, data );
};

/**
 * Allows you to append data to a value.
 * @implements File
 * @param {String} path - Specify a target file path.
 * @param {String} data - The data to be appended to the file.
 * @example
 * File.append( './text.txt', 'yay' );
 */

File.prototype.append = function ( filePath, data ) {

	var path = this.private.resolvePath( filePath );

	var FileWriter = Java.type( 'java.io.FileWriter' );

	var file = new FileWriter( path, true );

	file.write( data );
	file.close();
};

/**
 * Allows you to delete a file at the specified path.
 * @implements File
 * @param {String} path - Specify a target file path for deletion.
 * @example
 * File.delete( './text.txt' );
 */

File.prototype.delete = function ( filePath ) {

	var path = this.private.resolvePath( filePath );

	new java.io.File( path ).delete();
};

module.exports = File;
<commit_msg>Directory examples<commit_after>'use strict';

/**
 * @namespace
 */

var File = new Class( function ( file ) {

	this.private.fileInfo = file;
} );

File.prototype.private.resolvePath = function ( filePath ) {

	var isAbsolute = ( new java.io.File( filePath ) ).isAbsolute();

	var path = filePath;

	if ( !isAbsolute ) {
		path = java.nio.file.Paths.get( this.private.fileInfo.__dirname, filePath ).toString();
	}

	return path;
};

/**
 * Allows you to read and return the value of a file.
 * @implements File
 * @param {String} path - Specify a target text file to read.
 * @return {String}
 * @example
 * var data = File.read( './text.txt' );
 */

File.prototype.read = function ( filePath ) {

	var path = this.private.resolvePath( filePath );

	var contents = [];
	var line     = undefined;

	var file = new java.io.File( path );

	if ( file.exists() ) {

		var fileReader = new java.io.FileReader( path );

		var bufferReader = new java.io.BufferedReader( fileReader );

		while ( ( line = bufferReader.readLine() ) !== null ) {
			contents.push( line );
		}

		bufferReader.close();
		fileReader.close();

		return contents.join( '\n' );

	} else {
		console.log( '[ERROR]'.orange() + ' File not found:\n' + path + ':' + '\n' );
	}
};

/**
 * Allows you to write data to a file.
 * @implements File
 * @param {String} path - Specify a target file path.
 * @param {String} [data] - The data to be written to the file.
 * @example
 * File.write( './text.txt' );
 * // or
 * File.write( './text.txt', 'yay' );
 */

File.prototype.write = function ( filePath, data ) {

	var path = this.private.resolvePath( filePath );

	var FileWriter = Java.type( 'java.io.FileWriter' );

	var file = new FileWriter( path );

	file.write( data || '' );
	file.close();
};

/**
 * Alias for File.write().
 * @implements File
 * @param {String} path - Specify a target file path.
 * @param {String} [data] - The data to be written to the file.
 * @example
 * File.create( './text.txt' );
 * // or
 * File.create( './text.txt', 'yay' );
 */

File.prototype.create = function ( filePath, data ) {

	this.write( filePath, data );
};

/**
 * Allows you to append data to a value.
 * @implements File
 * @param {String} path - Specify a target file path.
 * @param {String} data - The data to be appended to the file.
 * @example
 * File.append( './text.txt', 'yay' );
 */

File.prototype.append = function ( filePath, data ) {

	var path = this.private.resolvePath( filePath );

	var FileWriter = Java.type( 'java.io.FileWriter' );

	var file = new FileWriter( path, true );

	file.write( data );
	file.close();
};

/**
 * Allows you to delete a file at the specified path.
 * @implements File
 * @param {String} path - Specify a target file path for deletion.
 * @example
 * File.delete( './text.txt' );
 */

File.prototype.delete = function ( filePath ) {

	var path = this.private.resolvePath( filePath );

	new java.io.File( path ).delete();
};

module.exports = File;
<|endoftext|>


<commit_before>var rocketChatIframe = { rcAvailableInIframe: false, iframeLoad: false, url: '' };
var handler = function () {
	return {
		set: function (target, key, value) {
			target[key] = value;
			if (target.rcAvailableInIframe && target.iframeLoad && window.iframeEl.src.length !== target.url.length) {
				window.iframeEl.src = target.url;
				var rocketChatIcon = document.querySelector('.js-rocketchat-icon');
				if (rocketChatIcon) {
					rocketChatIcon.classList.remove('display-none');
				}
			}
			return true;
		}
	};
};
var rocketChatProxy = new Proxy(rocketChatIframe, handler());
<commit_msg>added: delay to show chat button<commit_after>var rocketChatIframe = { rcAvailableInIframe: false, iframeLoad: false, url: '' };
var handler = function () {
	return {
		set: function (target, key, value) {
			target[key] = value;
			if (target.rcAvailableInIframe && target.iframeLoad && window.iframeEl.src.length !== target.url.length) {
				window.iframeEl.src = target.url;
				var rocketChatIcon = document.querySelector('.js-rocketchat-icon');
				if (rocketChatIcon) {
				  setTimeout(function () {
            rocketChatIcon.classList.remove('display-none');
          }, 3000)
				}
			}
			return true;
		}
	};
};
var rocketChatProxy = new Proxy(rocketChatIframe, handler());
<|endoftext|>


<commit_before>import React from 'react';

class StopList extends React.Component {
  render() {
    return (

<Stop />

    )
  }
}

export default StopList;
<commit_msg>update.<commit_after>import React from 'react';

class StopList extends React.Component {
  render() {
    return (

<Stop />

<Stop />

<Stop />

    )
  }
}

export default StopList;
<|endoftext|>


<commit_before>import Ember from "ember";
import DS from "ember-data";

const {
  get,
  inject: { service }
} = Ember;

export default DS.JSONAPIAdapter.extend({
  namespace: 'api',
  drupalMapper: service(),

  pathForType(modelName) {
    let drupalMapper = get(this, 'drupalMapper'),
        entity = drupalMapper.entityFor(modelName),
        bundle = drupalMapper.bundleFor(modelName);
    return entity + '/' + bundle;
  },

  buildQuery(snapshot) {
    let query = this._super(...arguments);
    query._format = 'api_json';
    return query;
  },

  query(store, type, query) {
    let drupalQuery = { filter: {} },
        queryFields = Object.keys(query),
        mapper = get(this, 'drupalMapper');

    queryFields.forEach((field) => {
      let fieldName = mapper.fieldName(type.modelName, field);
      drupalQuery.filter[fieldName] = drupalQuery.filter[fieldName] || {};
      drupalQuery.filter[fieldName]['value'] = query[field];
    });

    var url = this.buildURL(type.modelName, null, null, 'query', drupalQuery);

    if (this.sortQueryParams) {
      query = this.sortQueryParams(drupalQuery);
    }
    return this.ajax(url, 'GET', { data: query });
  },
});<commit_msg>Add _format when constructing store.query request<commit_after>import Ember from "ember";
import DS from "ember-data";

const {
  get,
  inject: { service }
} = Ember;

export default DS.JSONAPIAdapter.extend({
  namespace: 'api',
  drupalMapper: service(),

  pathForType(modelName) {
    let drupalMapper = get(this, 'drupalMapper'),
        entity = drupalMapper.entityFor(modelName),
        bundle = drupalMapper.bundleFor(modelName);
    return entity + '/' + bundle;
  },

  buildQuery(snapshot) {
    let query = this._super(...arguments);
    query._format = 'api_json';
    return query;
  },

  query(store, type, query) {
    let drupalQuery = { filter: {} },
        queryFields = Object.keys(query),
        mapper = get(this, 'drupalMapper');

    queryFields.forEach((field) => {
      let fieldName = mapper.fieldName(type.modelName, field);
      drupalQuery.filter[fieldName] = drupalQuery.filter[fieldName] || {};
      drupalQuery.filter[fieldName]['value'] = query[field];
    });

    var url = this.buildURL(type.modelName, null, null, 'query', drupalQuery);

    if (this.sortQueryParams) {
      query = this.sortQueryParams(drupalQuery);
    }

    query._format = 'api_json';
    return this.ajax(url, 'GET', { data: query });
  },
});<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Relay from 'react-relay';
import { Link } from 'react-router';
import { ListGroup, Glyphicon } from 'react-bootstrap';
import { EntryContainer, Entry } from './Entry';
import Intro from './Intro';
import Request, { RequestContainer } from './Request';
import _ from 'lodash';

export class Timeline extends Component {
    static propTypes = {
        viewer: React.PropTypes.object.isRequired,
    }

    constructor(props) {
        super(props);
        this.state = {
            hasEntries: props.viewer.role.entries.edges.length
        };
    }

    renderEntries() {
        return this.props.viewer.role.entries.edges.map((entry) => {
            if (this.props.relay) {
                return (<EntryContainer key={entry.node.id} entry={entry.node} />);
            } else {
                return (<Entry key={entry.node.id} entry={entry.node} />);
            }

        });
    }

    renderRequests() {
        if (this.props.viewer.role.requests.edges.length) {
            var request = _.first(this.props.viewer.role.requests.edges).node
            if (this.props.relay) {
                return (

                        <RequestContainer {...request} />

                );
            } else {
                return (

                        <Request {...request} />

                );
            }
        }
    }

    render() {
        return (

                    <Link className="btn" to={'/add'}>
                        <Glyphicon glyph="plus"/> {this.state.hasEntries ? 'Add New Entry' : 'Get Started'}</Link>

                {this.renderRequests()}
                <ListGroup componentClass="div">
                    {this.renderEntries()}
                    {!this.state.hasEntries &&
                        <Intro />
                    }
                </ListGroup>

        );
    }
}

export const TimelineContainer = Relay.createContainer(Timeline, {
    initialVariables: {
        first: 100,
    },
    fragments: {
        viewer: () => Relay.QL`
        fragment on Viewer {
            role {
                ... on Creator {
                    happyCount
                    sadCount
                    entries(first: $first) {
                        edges {
                            node {
                                id,
                                ${EntryContainer.getFragment('entry')}
                            }
                        }
                    }
                    requests(first: $first) {
                        edges {
                            node {
                                id,
                                _id,
                                request {
                                    id
                                    from
                                    to
                                    region
                                }
                                seen
                            }
                        }
                    }
                }
            }
        }`,
    }
});
<commit_msg>compress request in timeline<commit_after>import React, { Component } from 'react';
import Relay from 'react-relay';
import { Link } from 'react-router';
import { ListGroup, Glyphicon } from 'react-bootstrap';
import { EntryContainer, Entry } from './Entry';
import Intro from './Intro';
import Request, { RequestContainer } from './Request';
import _ from 'lodash';

export class Timeline extends Component {
    static propTypes = {
        viewer: React.PropTypes.object.isRequired,
    }

    constructor(props) {
        super(props);
        this.state = {
            hasEntries: props.viewer.role.entries.edges.length
        };
    }

    renderEntries() {
        return this.props.viewer.role.entries.edges.map((entry) => {
            if (this.props.relay) {
                return (<EntryContainer key={entry.node.id} entry={entry.node} />);
            } else {
                return (<Entry key={entry.node.id} entry={entry.node} />);
            }

        });
    }

    renderRequests() {
        if (this.props.viewer.role.requests.edges.length) {
            var request = _.first(this.props.viewer.role.requests.edges).node
            if (this.props.relay) {
                return (
                    <RequestContainer {...request} />
                );
            } else {
                return (
                    <Request {...request} />
                );
            }
        }
    }

    render() {
        return (

                        {this.renderRequests()}

                    <Link className="btn" to={'/add'}>
                        <Glyphicon glyph="plus"/> {this.state.hasEntries ? 'Add New Entry' : 'Get Started'}
                    </Link>

                <ListGroup componentClass="div">
                    {this.renderEntries()}
                    {!this.state.hasEntries &&
                        <Intro />
                    }
                </ListGroup>

        );
    }
}

export const TimelineContainer = Relay.createContainer(Timeline, {
    initialVariables: {
        first: 100,
    },
    fragments: {
        viewer: () => Relay.QL`
        fragment on Viewer {
            role {
                ... on Creator {
                    happyCount
                    sadCount
                    entries(first: $first) {
                        edges {
                            node {
                                id,
                                ${EntryContainer.getFragment('entry')}
                            }
                        }
                    }
                    requests(first: $first) {
                        edges {
                            node {
                                id,
                                _id,
                                request {
                                    id
                                    from
                                    to
                                    region
                                }
                                seen
                            }
                        }
                    }
                }
            }
        }`,
    }
});
<|endoftext|>


<commit_before>/**
 * This file is part of the @iconify/tools package.
 *
 * (c) Vjacheslav Trushkin <cyberalien@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

'use strict';

const fs = require('fs');
const helpers = require('../helpers');

const iconType = `interface IconifyIcon {
    body: string;
	left?: number;
	top?: number;
	width?: number;
	height?: number;
	rotate?: number;
	hFlip?: boolean;
	vFlip?: boolean;
}
declare const data: IconifyIcon;
export default data;
`;

const iconLegacyType = `interface LegacyIconifyIcon {
    body: string;
	left?: number;
	top?: number;
	width?: number;
	height?: number;
	rotate?: number;
	hFlip?: boolean;
    vFlip?: boolean;
    // Legacy stuff
    inlineTop?: number;
    inlineHeight?: number;
    verticalAlign?: number;
}
declare const data: LegacyIconifyIcon;
export default data;
`;

const legacyAttributes = ['inlineTop', 'inlineHeight', 'verticalAlign'];

const defaults = {
	// True if .d.ts files should be exported
	definitions: true,

	// Directory for uncompiled files. Set to non-string (false, null) to disable
	sources: '/src',

	// Directory for compiled files. Set to non-string (false, null) to disable
	compiled: '',

	// Export package.json, boolean or file name
	package: true,

	// Export README.md, boolean or file name
	readme: true,

	// CommonJS syntax
	commonjs: true,

	// Information for package.json and README.md:
	// Package name
	name: '@iconify/icons-{prefix}',

	// Version number
	version: null,

	// Array of icon samples
	samples: [],

	// Collection information
	info: null,
};

const transformKeys = ['rotate', 'vFlip', 'hFlip'];

const positionAttributes = ['left', 'top'];

const inlineAttributes = ['inlineHeight', 'inlineTop', 'verticalAlign'];

/**
 * Convert icon name to camelCase with optional "Icon" suffix
 *
 * @param {string} name
 * @return {string}
 */
const iconName = (name, addSuffix = true) => {
	let parts = name.split(/[-:]/),
		result = parts.shift();

	if (name.charCodeAt(0) < 97 || name.charCodeAt(0) > 122) {
		// Not a-z - add "icon" at start so variable doesn't start with invalid character
		parts.unshift('icon');
	} else if (parts.length < 1 && addSuffix) {
		// Add "Icon" to avoid reserved keywords
		parts.push('icon');
	}

	parts.forEach((part) => {
		result += part.slice(0, 1).toUpperCase() + part.slice(1);
	});

	return result;
};

/**
 * Export collection to js files
 *
 * @param {Collection} collection Collection to export
 * @param {string} [dir] Target directory
 * @param {object} [options] Options
 * @returns {Promise}
 */
module.exports = (collection, dir, options) => {
	return new Promise((fulfill, reject) => {
		options = options === void 0 ? Object.create(null) : options;
		Object.keys(defaults).forEach((key) => {
			if (options[key] === void 0) {
				options[key] = defaults[key];
			}
		});

		let name =
				options.info && options.info.name
					? options.info.name
					: collection.prefix,
			packageName = options.name.replace('{prefix}', collection.prefix);

		/**
		 * Export package.json
		 */
		const exportPackage = () => {
			let result = {
				name: packageName,
				description: 'Iconify icon components for ' + name,
			};

			if (typeof options.version === 'string') {
				result.version = options.version;
			}

			if (options.info) {
				let infoBlock = {};
				[
					'name',
					'version',
					'author',
					'url',
					'license',
					'licenseURL',
					'palette',
				].forEach((key) => {
					if (options.info[key] !== void 0) {
						infoBlock[key] = options.info[key];
					}
				});
				if (Object.keys(infoBlock).length > 1) {
					result.iconsSet = infoBlock;
				}
			}

			result.bugs = 'https://github.com/iconify/iconify/issues';
			result.homepage = 'https://github.com/iconify/iconify';

			fs.writeFileSync(
				dir + '/package.json',
				JSON.stringify(result, null, '\t'),
				'utf8'
			);
		};

		/**
		 * Export README.md
		 */
		const exportReadme = () => {
			const templatesDir = __dirname + '/templates';
			const replacements = {
				iconSetName: name,
				packageName: packageName,
				iconSetPrefix: collection.prefix,
			};

			/**
			 * Replace all key/value pairs in text
			 */
			function replaceContent(content, replacements) {
				(replacements instanceof Array ? replacements : [replacements]).forEach(
					(list) => {
						Object.keys(list).forEach((key) => {
							const value = list[key];

							let start = 0;
							let pos;

							while ((pos = content.indexOf(key, start)) !== -1) {
								content =
									content.slice(0, pos) +
									value +
									content.slice(pos + key.length);
								start = pos + value.length;
							}
						});
					}
				);
				return content;
			}

			// Find all language specific templates
			const languages = [];
			fs.readdirSync(templatesDir).forEach((file) => {
				let parts = file.split('.');
				if (parts.length !== 2 || parts.pop() !== 'md') {
					return;
				}
				parts = parts[0].split('-');
				if (parts.shift() !== 'sample') {
					return;
				}
				const lang = parts.shift();
				if (languages.indexOf(lang) === -1) {
					languages.push(lang);
				}
			});

			// Parse all languages
			languages.forEach((lang) => {
				const codeSamples = [];
				options.samples.forEach((sample, index) => {
					// Get sample name
					let sampleReplacements = {
						sampleFilename: sample,
						sampleIconShortName: iconName(sample, false),
						sampleIconName: iconName(sample),
					};

					// Get template
					let content;
					try {
						content = fs.readFileSync(
							`${templatesDir}/sample-${lang}-${index}.md`,
							'utf8'
						);
					} catch (err) {
						try {
							content = fs.readFileSync(
								`${templatesDir}/sample-${lang}.md`,
								'utf8'
							);
						} catch (err) {
							return;
						}
					}

					// Replace content
					content = replaceContent(content, [sampleReplacements, replacements]);
					codeSamples.push(content.trim());
				});
				replacements['`samples.' + lang + '`'] = codeSamples.join('\n\n');
			});

			// Get content
			let content = fs
				.readFileSync(templatesDir + '/component.md', 'utf8')
				.trim();

			// Author information
			if (
				options.info &&
				options.info.author !== void 0 &&
				options.info.name !== void 0
			) {
				const phrases = {
					author: 'Icons author: ',
					url: 'Website: ',
					license: 'License: ',
					licenseURL: 'License URL: ',
				};

				const list = [];

				// Author name and website
				if (typeof options.info.author === 'object') {
					const author = options.info.author;
					if (typeof author.name === 'string') {
						list.push(phrases.author + author.name);
						if (typeof author.url === 'string') {
							list.push(phrases.url + author.url);
						}
					}
				} else if (typeof options.info.author === 'string') {
					list.push(phrases.author + options.info.author);
				}

				// License
				if (typeof options.info.license === 'object') {
					const license = options.info.license;
					if (typeof license.title === 'string') {
						list.push(phrases.license + license.title);
						if (typeof license.url === 'string') {
							list.push(phrases.licenseURL + license.url);
						}
					}
				} else if (typeof options.info.license === 'string') {
					list.push(phrases.license + options.info.license);
				}

				if (list.length) {
					const infoReplacements = {
						iconSetInfo: list.join('\n\n'),
					};

					let info = fs.readFileSync(templatesDir + '/info.md', 'utf8');
					content += '\n\n' + replaceContent(info, infoReplacements).trim();
				}
			}

			// Replace content
			content = replaceContent(content, replacements) + '\n';

			// Check if there are missing samples
			if (content.indexOf('`samples.') !== -1) {
				throw new Error('Did not replace all samples in generated README.md');
			}

			fs.writeFileSync(dir + '/README.md', content, 'utf8');
		};

		/**
		 * Export typescript file
		 *
		 * @param {string} filename
		 * @param {boolean} isLegacy
		 */
		const exportTS = (filename, isLegacy = false) => {
			fs.writeFileSync(
				filename + '.d.ts',
				isLegacy ? iconLegacyType : iconType
			);
		};

		/**
		 * Export icon
		 *
		 * @param {string} name
		 * @param {object} data
		 */
		const exportIcon = (name, data) => {
			let content = JSON.stringify(data, null, '\t'),
				code;

			// Check if data has legacy attributes
			let isLegacy = false;
			if (options.definitions) {
				legacyAttributes.forEach((attr) => {
					if (data[attr] !== void 0) {
						isLegacy = true;
					}
				});
			}

			// Save uncompiled file
			if (typeof options.sources === 'string') {
				code = 'let data = ' + content + ';\nexport default data;\n';
				fs.writeFileSync(
					dir + options.sources + '/' + name + '.js',
					code,
					'utf8'
				);
				if (options.definitions) {
					exportTS(dir + options.sources + '/' + name, isLegacy);
				}
			}

			// Save compiled file
			if (typeof options.compiled === 'string') {
				code = 'var data = ' + content + ';\n';
				if (options.commonjs) {
					code += 'exports.__esModule = true;\nexports.default = data;\n';
				} else {
					code += 'export default data;\n';
				}
				fs.writeFileSync(
					dir + options.compiled + '/' + name + '.js',
					code,
					'utf8'
				);
				if (options.definitions) {
					exportTS(dir + options.compiled + '/' + name, isLegacy);
				}
			}
		};

		// Prepare output directories
		if (typeof options.sources === 'string') {
			helpers.mkdir(dir + options.sources);
		}
		if (typeof options.compiled === 'string') {
			helpers.mkdir(dir + options.compiled);
		}

		// Get samples
		let samples = options.samples instanceof Array ? options.samples : [];
		if (samples.length < 3) {
			let icons = collection.keys(false);
			for (let i = 0; i < 3; i++) {
				samples[i] =
					samples[i] === void 0
						? icons[Math.floor((icons.length / 4) * (i + 1))]
						: samples[i];
			}
		}

		// Export all icons
		collection.forEach((svg, key, prefix) => {
			let json = {
				body: svg.getBody().replace(/\s*\n\s*/g, ''),
				width: svg.width,
				height: svg.height,
			};

			// Add left/top
			positionAttributes.forEach((attr) => {
				if (svg[attr] !== 0) {
					json[attr] = svg[attr];
				}
			});

			// Add transformations
			transformKeys.forEach((attr) => {
				if (svg[attr] !== void 0) {
					json[attr] = svg[attr];
				}
			});

			// Include inline attributes
			if (options.includeInline) {
				inlineAttributes.forEach((attr) => {
					if (svg[attr] !== void 0) {
						json[attr] = svg[attr];
					}
				});
			}

			exportIcon(key, json);

			// Export aliases
			(svg.aliases ? svg.aliases : []).forEach((alias) => {
				switch (typeof alias) {
					case 'string':
						if (collection.items[alias] === void 0) {
							exportIcon(alias, json);
						}
						return;

					case 'object':
						if (
							alias.name === void 0 ||
							collection.items[alias.name] !== void 0
						) {
							return;
						}

						let data = Object.assign({}, json);

						transformKeys.forEach((key) => {
							if (alias[key] === void 0) {
								return;
							}
							if (data[key] === void 0) {
								data[key] = alias[key];
								return;
							}

							let value = data[key];
							switch (key) {
								case 'rotate':
									value = (value + alias[key]) % 4;
									break;

								default:
									value = value !== alias[key];
							}

							if (!value) {
								delete data[key];
							} else {
								data[key] = value;
							}
						});
						exportIcon(alias.name, data);
				}
			});
		});

		if (options.package) {
			exportPackage();
		}

		if (options.readme) {
			exportReadme();
		}

		fulfill(collection);
	});
};
<commit_msg>Change options for components export<commit_after>/**
 * This file is part of the @iconify/tools package.
 *
 * (c) Vjacheslav Trushkin <cyberalien@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

'use strict';

const fs = require('fs');
const helpers = require('../helpers');

const iconType = `interface IconifyIcon {
    body: string;
	left?: number;
	top?: number;
	width?: number;
	height?: number;
	rotate?: number;
	hFlip?: boolean;
	vFlip?: boolean;
}
declare const data: IconifyIcon;
export default data;
`;

const iconLegacyType = `interface LegacyIconifyIcon {
    body: string;
	left?: number;
	top?: number;
	width?: number;
	height?: number;
	rotate?: number;
	hFlip?: boolean;
    vFlip?: boolean;
    // Legacy stuff
    inlineTop?: number;
    inlineHeight?: number;
    verticalAlign?: number;
}
declare const data: LegacyIconifyIcon;
export default data;
`;

const legacyAttributes = ['inlineTop', 'inlineHeight', 'verticalAlign'];

const defaults = {
	// True if .d.ts files should be exported
	definitions: true,

	// Export package.json, boolean or file name
	package: true,

	// Export README.md, boolean or file name
	readme: true,

	// CommonJS syntax
	commonjs: true,

	// Information for package.json and README.md:
	// Package name
	name: '@iconify/icons-{prefix}',

	// Version number
	version: null,

	// Array of icon samples
	samples: [],

	// Collection information
	info: null,
};

const transformKeys = ['rotate', 'vFlip', 'hFlip'];

const positionAttributes = ['left', 'top'];

const inlineAttributes = ['inlineHeight', 'inlineTop', 'verticalAlign'];

/**
 * Convert icon name to camelCase with optional "Icon" suffix
 *
 * @param {string} name
 * @return {string}
 */
const iconName = (name, addSuffix = true) => {
	let parts = name.split(/[-:]/),
		result = parts.shift();

	if (name.charCodeAt(0) < 97 || name.charCodeAt(0) > 122) {
		// Not a-z - add "icon" at start so variable doesn't start with invalid character
		parts.unshift('icon');
	} else if (parts.length < 1 && addSuffix) {
		// Add "Icon" to avoid reserved keywords
		parts.push('icon');
	}

	parts.forEach((part) => {
		result += part.slice(0, 1).toUpperCase() + part.slice(1);
	});

	return result;
};

/**
 * Export collection to js files
 *
 * @param {Collection} collection Collection to export
 * @param {string} [dir] Target directory
 * @param {object} [options] Options
 * @returns {Promise}
 */
module.exports = (collection, dir, options) => {
	return new Promise((fulfill, reject) => {
		options = options === void 0 ? Object.create(null) : options;
		Object.keys(defaults).forEach((key) => {
			if (options[key] === void 0) {
				options[key] = defaults[key];
			}
		});

		let name =
				options.info && options.info.name
					? options.info.name
					: collection.prefix,
			packageName = options.name.replace('{prefix}', collection.prefix);

		/**
		 * Export package.json
		 */
		const exportPackage = () => {
			let result = {
				name: packageName,
				description: 'Iconify icon components for ' + name,
			};

			if (typeof options.version === 'string') {
				result.version = options.version;
			}

			if (options.info) {
				let infoBlock = {};
				[
					'name',
					'version',
					'author',
					'url',
					'license',
					'licenseURL',
					'palette',
				].forEach((key) => {
					if (options.info[key] !== void 0) {
						infoBlock[key] = options.info[key];
					}
				});
				if (Object.keys(infoBlock).length > 1) {
					result.iconsSet = infoBlock;
				}
			}

			result.bugs = 'https://github.com/iconify/iconify/issues';
			result.homepage = 'https://github.com/iconify/iconify';

			fs.writeFileSync(
				dir + '/package.json',
				JSON.stringify(result, null, '\t'),
				'utf8'
			);
		};

		/**
		 * Export README.md
		 */
		const exportReadme = () => {
			const templatesDir = __dirname + '/templates';
			const replacements = {
				iconSetName: name,
				packageName: packageName,
				iconSetPrefix: collection.prefix,
			};

			/**
			 * Replace all key/value pairs in text
			 */
			function replaceContent(content, replacements) {
				(replacements instanceof Array ? replacements : [replacements]).forEach(
					(list) => {
						Object.keys(list).forEach((key) => {
							const value = list[key];

							let start = 0;
							let pos;

							while ((pos = content.indexOf(key, start)) !== -1) {
								content =
									content.slice(0, pos) +
									value +
									content.slice(pos + key.length);
								start = pos + value.length;
							}
						});
					}
				);
				return content;
			}

			// Find all language specific templates
			const languages = [];
			fs.readdirSync(templatesDir).forEach((file) => {
				let parts = file.split('.');
				if (parts.length !== 2 || parts.pop() !== 'md') {
					return;
				}
				parts = parts[0].split('-');
				if (parts.shift() !== 'sample') {
					return;
				}
				const lang = parts.shift();
				if (languages.indexOf(lang) === -1) {
					languages.push(lang);
				}
			});

			// Parse all languages
			languages.forEach((lang) => {
				const codeSamples = [];
				options.samples.forEach((sample, index) => {
					// Get sample name
					let sampleReplacements = {
						sampleFilename: sample,
						sampleIconShortName: iconName(sample, false),
						sampleIconName: iconName(sample),
					};

					// Get template
					let content;
					try {
						content = fs.readFileSync(
							`${templatesDir}/sample-${lang}-${index}.md`,
							'utf8'
						);
					} catch (err) {
						try {
							content = fs.readFileSync(
								`${templatesDir}/sample-${lang}.md`,
								'utf8'
							);
						} catch (err) {
							return;
						}
					}

					// Replace content
					content = replaceContent(content, [sampleReplacements, replacements]);
					codeSamples.push(content.trim());
				});
				replacements['`samples.' + lang + '`'] = codeSamples.join('\n\n');
			});

			// Get content
			let content = fs
				.readFileSync(templatesDir + '/component.md', 'utf8')
				.trim();

			// Author information
			if (
				options.info &&
				options.info.author !== void 0 &&
				options.info.name !== void 0
			) {
				const phrases = {
					author: 'Icons author: ',
					url: 'Website: ',
					license: 'License: ',
					licenseURL: 'License URL: ',
				};

				const list = [];

				// Author name and website
				if (typeof options.info.author === 'object') {
					const author = options.info.author;
					if (typeof author.name === 'string') {
						list.push(phrases.author + author.name);
						if (typeof author.url === 'string') {
							list.push(phrases.url + author.url);
						}
					}
				} else if (typeof options.info.author === 'string') {
					list.push(phrases.author + options.info.author);
				}

				// License
				if (typeof options.info.license === 'object') {
					const license = options.info.license;
					if (typeof license.title === 'string') {
						list.push(phrases.license + license.title);
						if (typeof license.url === 'string') {
							list.push(phrases.licenseURL + license.url);
						}
					}
				} else if (typeof options.info.license === 'string') {
					list.push(phrases.license + options.info.license);
				}

				if (list.length) {
					const infoReplacements = {
						iconSetInfo: list.join('\n\n'),
					};

					let info = fs.readFileSync(templatesDir + '/info.md', 'utf8');
					content += '\n\n' + replaceContent(info, infoReplacements).trim();
				}
			}

			// Replace content
			content = replaceContent(content, replacements) + '\n';

			// Check if there are missing samples
			if (content.indexOf('`samples.') !== -1) {
				throw new Error('Did not replace all samples in generated README.md');
			}

			fs.writeFileSync(dir + '/README.md', content, 'utf8');
		};

		/**
		 * Export typescript file
		 *
		 * @param {string} filename
		 * @param {boolean} isLegacy
		 */
		const exportTS = (filename, isLegacy = false) => {
			fs.writeFileSync(
				filename + '.d.ts',
				isLegacy ? iconLegacyType : iconType
			);
		};

		/**
		 * Export icon
		 *
		 * @param {string} name
		 * @param {object} data
		 */
		const exportIcon = (name, data) => {
			let content = JSON.stringify(data, null, '\t'),
				code;

			// Check if data has legacy attributes
			let isLegacy = false;
			if (options.definitions) {
				legacyAttributes.forEach((attr) => {
					if (data[attr] !== void 0) {
						isLegacy = true;
					}
				});
			}

			// Save files
			code = 'var data = ' + content + ';\n';
			if (options.commonjs) {
				code += 'exports.__esModule = true;\nexports.default = data;\n';
			} else {
				code += 'export default data;\n';
			}
			fs.writeFileSync(dir + '/' + name + '.js', code, 'utf8');
			if (options.definitions) {
				exportTS(dir + '/' + name, isLegacy);
			}
		};

		// Prepare output directory
		helpers.mkdir(dir);

		// Get samples
		let samples = options.samples instanceof Array ? options.samples : [];
		if (samples.length < 3) {
			let icons = collection.keys(false);
			for (let i = 0; i < 3; i++) {
				samples[i] =
					samples[i] === void 0
						? icons[Math.floor((icons.length / 4) * (i + 1))]
						: samples[i];
			}
		}

		// Export all icons
		collection.forEach((svg, key, prefix) => {
			let json = {
				body: svg.getBody().replace(/\s*\n\s*/g, ''),
				width: svg.width,
				height: svg.height,
			};

			// Add left/top
			positionAttributes.forEach((attr) => {
				if (svg[attr] !== 0) {
					json[attr] = svg[attr];
				}
			});

			// Add transformations
			transformKeys.forEach((attr) => {
				if (svg[attr] !== void 0) {
					json[attr] = svg[attr];
				}
			});

			// Include inline attributes
			if (options.includeInline) {
				inlineAttributes.forEach((attr) => {
					if (svg[attr] !== void 0) {
						json[attr] = svg[attr];
					}
				});
			}

			exportIcon(key, json);

			// Export aliases
			(svg.aliases ? svg.aliases : []).forEach((alias) => {
				switch (typeof alias) {
					case 'string':
						if (collection.items[alias] === void 0) {
							exportIcon(alias, json);
						}
						return;

					case 'object':
						if (
							alias.name === void 0 ||
							collection.items[alias.name] !== void 0
						) {
							return;
						}

						let data = Object.assign({}, json);

						transformKeys.forEach((key) => {
							if (alias[key] === void 0) {
								return;
							}
							if (data[key] === void 0) {
								data[key] = alias[key];
								return;
							}

							let value = data[key];
							switch (key) {
								case 'rotate':
									value = (value + alias[key]) % 4;
									break;

								default:
									value = value !== alias[key];
							}

							if (!value) {
								delete data[key];
							} else {
								data[key] = value;
							}
						});
						exportIcon(alias.name, data);
				}
			});
		});

		if (options.package) {
			exportPackage();
		}

		if (options.readme) {
			exportReadme();
		}

		fulfill(collection);
	});
};
<|endoftext|>