<commit_before>import InputCloneService from '../../../../js/Repeater/InputCloneService';
import $ from 'jquery';

describe('InputCloneService', () => {
    let inputCloneService;

    beforeEach(() => {
        inputCloneService = new InputCloneService();
    });

    describe('clone', () => {
        it('<select/>', () => {
            const $select = $(`
                <select>
                    <option value="choose">Choose a colour</option>
                    <option value="red">Red</option>
                    <option value="blue">Blue</option>
                </select>
            `);
            let clone;

            $select.val('blue');
            clone = inputCloneService.clone($select[0]);

            expect(clone.value).to.equal('blue');
        });
    });
});
<commit_msg>improve inputCloneService coverage<commit_after>const InputCloneService = require('../../../../js/Repeater/InputCloneService');
const PulsarFormComponent = require('../../../../js/PulsarFormComponent');
const QueryService = require('../../../../js/utilities/QueryService');
const $ = require('jquery');

describe('InputCloneService', () => {
    let inputCloneService;
    let pulsarFormComponentStub;
    let queryServiceStub;

    beforeEach(() => {
        pulsarFormComponentStub = sinon.createStubInstance(PulsarFormComponent);
        queryServiceStub = sinon.createStubInstance(QueryService);
        inputCloneService = new InputCloneService(
            pulsarFormComponentStub,
            queryServiceStub
        );

        $.fn.select2 = sinon.stub();
        queryServiceStub.getAttr.withArgs('select2-data').returns('data-select2-data');
    });

    afterEach(() => {
        $.fn.select2.reset();
    });

    describe('clone', () => {
        describe('text', () => {
           it('should return a deep clone for inputs that do not require manual intervention', () => {
                const $wrap = $('
<input type="text"/>
');
                const clone = inputCloneService.clone($wrap.find('input')[0]);
                const $cloneWrap = $('

').append(clone);

                expect($wrap.html()).to.equal($cloneWrap.html());
           });
        });

        describe('select', () => {
            it('should clone a select-one input', () => {
                const $select = $(`
                    <select>
                        <option value="choose">Choose a colour</option>
                        <option value="red">Red</option>
                        <option value="blue">Blue</option>
                    </select>
                `);

                $select.find('[value="blue"]').prop('selected', true);

                const clone = inputCloneService.clone($select[0]);

                expect(clone.value).to.equal('blue');
            });

            it('should clone a select-multiple input', () => {
                const $select = $(`
                    <select multiple="true">
                        <option value="choose">Choose a colour</option>
                        <option value="red">Red</option>
                        <option value="blue">Blue</option>
                    </select>
                `);

                $select.find('[value="blue"]').prop('selected', true);
                $select.find('[value="red"]').prop('selected', true);

                const clone = inputCloneService.clone($select[0]);

                expect(clone.children[0].selected).to.be.false;
                expect(clone.children[1].selected).to.be.true;
                expect(clone.children[2].selected).to.be.true;
            });

            it('should destroy a select2 and store data as an attribute', () => {
                const $select = $(`
                    <select class="js-select2">
                        <option value="choose">Choose a colour</option>
                        <option value="red">Red</option>
                        <option value="blue">Blue</option>
                    </select>
                `);

                $select.data('select2', {foo: 'bar'});
                $.fn.select2.withArgs('data').returns({foo: 'bar'});

                inputCloneService.clone($select[0]);

                expect($.fn.select2).to.have.been.calledTwice;
                expect($.fn.select2).to.have.been.calledWith('data');
                expect($.fn.select2).to.have.been.calledWith('destroy');
                expect($select[0].getAttribute('data-select2-data')).to.equal(JSON.stringify({
                    foo: 'bar'
                }));
            });
        });
    });
});
<|endoftext|>


<commit_before>const browser = typeof window !== 'undefined';

let fetch;
let FormData;
if (browser) {
  fetch = window.fetch; // eslint-disable-line no-undef
  FormData = window.FormData; // eslint-disable-line no-undef
} else {
  fetch = require('node-fetch');
  FormData = require('./FormData');
}

function convertToBuffer(ab) {
  function str2ab(str) {
    const buffer = new ArrayBuffer(str.length * 2);
    const view = new Uint16Array(buffer);
    for (var i = 0, strLen = str.length; i < strLen; i++) view[i] = str.charCodeAt(i);
    return buffer;
  }

  if (typeof ab === 'string') ab = str2ab(ab);
  return Buffer.from(ab);
}

class Fetcher {
  constructor(method, url) {
    this.url = url;
    this.method = method.toUpperCase();
    this.headers = {};
    this.data = null;
  }

  set(name, value) {
    this.headers[name] = value;
    return this;
  }

  attach(name, data, filename) {
    const form = this._getFormData();
    this.set('Content-Type', `multipart/form-data; boundary=${form.boundary}`);
    form.append(name, data, filename);
    this.data = form;
    return this;
  }

  send(data) {
    if (typeof data === 'object') {
      this.set('Content-Type', 'application/json');
      this.data = JSON.stringify(data);
    } else {
      this.data = data;
    }
    return this;
  }

  end(cb) {
    // in a browser, the response is actually immutable, so we make a new one
    let response = {
      headers: {},
      text: '',
      body: {},
    };
    const data = this.data ? this.data.end ? this.data.end() : this.data : null;
    return fetch(this.url, {
      method: this.method,
      headers: this.headers,
      body: data,
    }).then((res) => {
      const ctype = res.headers.get('Content-Type');
      if (ctype === 'application/json') {
        return res.text().then((t) => {
          response.text = t;
          response.body = JSON.parse(t);
          return res;
        });
      } else {
        return (browser ? res.arrayBuffer() : res.buffer())
        .then((b) => {
          if (b instanceof ArrayBuffer) b = convertToBuffer(b);
          response.body = b;
          response.text = b.toString();
          return res;
        });
      }
    })
    .then((res) => {
      const body = response.body;
      const text = response.text;
      Object.assign(response, res);
      response.body = body;
      response.text = text;
      if (res.headers.raw) {
        for (const [name, value] of Object.entries(res.headers.raw())) response.headers[name] = value[0];
      } else {
        for (const [name, value] of res.headers.entries()) response.headers[name] = value;
      }
      if (['4', '5'].includes(response.status.toString().substr(0, 1))) return cb(response, response);
      return cb(null, response);
    })
    .catch((err) => {
      cb(err);
    });
  }

  then(s, f) {
    return new Promise((resolve, reject) => {
      this.end((err, res) => {
        if (err) reject(f(err));
        else resolve(s ? s(res) : null);
      });
    });
  }

  catch(f) {
    return this.then(null, f);
  }

  _getFormData() {
    if (!this._formData) this._formData = new FormData();
    return this._formData;
  }
}

const methods = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'];
for (const method of methods) Fetcher[method.toLowerCase()] = (url) => new Fetcher(method, url);

module.exports = Fetcher;
if (browser) window.Fetcher = Fetcher;
<commit_msg>add proper www url encoded form parsing<commit_after>const browser = typeof window !== 'undefined';

const querystring = require('querystring');

let fetch;
let FormData;
if (browser) {
  fetch = window.fetch; // eslint-disable-line no-undef
  FormData = window.FormData; // eslint-disable-line no-undef
} else {
  fetch = require('node-fetch');
  FormData = require('./FormData');
}

function convertToBuffer(ab) {
  function str2ab(str) {
    const buffer = new ArrayBuffer(str.length * 2);
    const view = new Uint16Array(buffer);
    for (var i = 0, strLen = str.length; i < strLen; i++) view[i] = str.charCodeAt(i);
    return buffer;
  }

  if (typeof ab === 'string') ab = str2ab(ab);
  return Buffer.from(ab);
}

function parseWWWFormUrlEncoded(str) {
  const obj = {};
  for (const [k, v] of str.split('&').map(q => q.split('='))) obj[k] = v;
  return obj;
}

class Fetcher {
  constructor(method, url) {
    this.url = url;
    this.method = method.toUpperCase();
    this.headers = {};
    this.data = null;
  }

  set(name, value) {
    this.headers[name] = value;
    return this;
  }

  attach(name, data, filename) {
    const form = this._getFormData();
    this.set('Content-Type', `multipart/form-data; boundary=${form.boundary}`);
    form.append(name, data, filename);
    this.data = form;
    return this;
  }

  send(data) {
    if (typeof data === 'object') {
      this.set('Content-Type', 'application/json');
      this.data = JSON.stringify(data);
    } else {
      this.data = data;
    }
    return this;
  }

  end(cb) {
    // in a browser, the response is actually immutable, so we make a new one
    let response = {
      headers: {},
      text: '',
      body: {},
    };
    const data = this.data ? this.data.end ? this.data.end() : this.data : null;
    return fetch(this.url, {
      method: this.method,
      headers: this.headers,
      body: data,
    }).then((res) => {
      const ctype = res.headers.get('Content-Type');
      if (ctype === 'application/json') {
        return res.text().then((t) => {
          response.text = t;
          response.body = JSON.parse(t);
          return res;
        });
      } else if (ctype === 'application/x-www-form-urlencoded') {
        return res.text().then((t) => {
          response.text = t;
          response.body = parseWWWFormUrlEncoded(t);
          return res;
        });
      } else {
        return (browser ? res.arrayBuffer() : res.buffer())
        .then((b) => {
          if (b instanceof ArrayBuffer) b = convertToBuffer(b);
          response.body = b;
          response.text = b.toString();
          return res;
        });
      }
    })
    .then((res) => {
      const body = response.body;
      const text = response.text;
      Object.assign(response, res);
      response.body = body;
      response.text = text;
      if (res.headers.raw) {
        for (const [name, value] of Object.entries(res.headers.raw())) response.headers[name] = value[0];
      } else {
        for (const [name, value] of res.headers.entries()) response.headers[name] = value;
      }
      if (['4', '5'].includes(response.status.toString().substr(0, 1))) return cb(response, response);
      return cb(null, response);
    })
    .catch((err) => {
      cb(err);
    });
  }

  then(s, f) {
    return new Promise((resolve, reject) => {
      this.end((err, res) => {
        if (err) reject(f(err));
        else resolve(s ? s(res) : null);
      });
    });
  }

  catch(f) {
    return this.then(null, f);
  }

  _getFormData() {
    if (!this._formData) this._formData = new FormData();
    return this._formData;
  }
}

const methods = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'];
for (const method of methods) Fetcher[method.toLowerCase()] = (url) => new Fetcher(method, url);

module.exports = Fetcher;
if (browser) window.Fetcher = Fetcher;
<|endoftext|>


<commit_before>/*
Copyright 2016 First People's Cultural Council

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Colors from 'material-ui/lib/styles/colors';
import ColorManipulator from 'material-ui/lib/utils/color-manipulator';
import Spacing from 'material-ui/lib/styles/spacing';
import zIndex from 'material-ui/lib/styles/zIndex';

export default {
  spacing: Spacing,
  zIndex: zIndex,
  fontFamily: 'Arial, sans-serif',
  palette: {
    primary1Color: Colors.teal400,
    primary2Color: Colors.teal700,
    primary3Color: Colors.lightBlack,
    accent1Color: Colors.pinkA200,
    accent2Color: Colors.grey100,
    accent3Color: Colors.grey500,
    textColor: Colors.darkBlack,
    alternateTextColor: Colors.white,
    canvasColor: Colors.white,
    borderColor: Colors.grey300,
    disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3),
    pickerHeaderColor: Colors.teal400
  },
  wrapper: {
    backgroundColor: Colors.white
  }
};<commit_msg>Change accent color in Workspace theme so that toolbars aren't too faded<commit_after>/*
Copyright 2016 First People's Cultural Council

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Colors from 'material-ui/lib/styles/colors';
import ColorManipulator from 'material-ui/lib/utils/color-manipulator';
import Spacing from 'material-ui/lib/styles/spacing';
import zIndex from 'material-ui/lib/styles/zIndex';

export default {
  spacing: Spacing,
  zIndex: zIndex,
  fontFamily: 'Arial, sans-serif',
  palette: {
    primary1Color: Colors.teal400,
    primary2Color: Colors.teal700,
    primary3Color: Colors.lightBlack,
    accent1Color: Colors.pinkA200,
    accent2Color: "#529c95",
    accent3Color: Colors.grey500,
    textColor: Colors.darkBlack,
    alternateTextColor: Colors.white,
    canvasColor: Colors.white,
    borderColor: Colors.grey300,
    disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3),
    pickerHeaderColor: Colors.teal400
  },
  wrapper: {
    backgroundColor: Colors.white
  }
};<|endoftext|>


<commit_before>(function (moduleFactory) {
    if (typeof exports === "object") {
        module.exports = moduleFactory(require("lodash"), require("moment"));
    } else if (typeof define === "function" && define.amd) {
        define(["lodash", "moment"], moduleFactory);
    }
}(function (_, moment) {
/**
 * @module handlebars%moment
 * @description  Helpers providing [Moment.js](http://momentjs.com) functionality
 *
 *     var Handlebars = require("handlebars");
 *     var MomentHelper = require("handlebars.moment");
 *     MomentHelper.registerHelpers(Handlebars);
 *
 * @returns {object} MomentHelper instance
 */

    var MomentHelpers = function (Handlebars) {
        var momentFormatMap = {
            dates: "date",
            months: "month",
            years: "year",
            isoweekday: "isoWeekday",
            dayofyear: "dayOfYear",
            isoweek: "isoWeek",
            isoweeks: "isoWeek",
            weekyear: "weekYear",
            isoweekyear: "isoWeekYear",
            zoneabbr: "zoneAbbr",
            zonename: "zoneName",
            tostring: "toString",
            string: "toString",
            str: "toString",
            valueof: "valueOf",
            value: "valueOf",
            val: "valueOf",
            fromnow: "fromNow",
            daysinmonth: "daysInMonth",
            todate: "toDate",
            toarray: "toArray",
            array: "toArray",
            tojson: "toJSON",
            json: "toJSON",
            toisostring: "toISOString",
            isostring: "toISOString"
        };
        var weekdayMap = {
            L: "dddd",
            S: "ddd",
            XS: "dd"
        };

        /**
         * @template moment
         * @block helper
         * @param {string|date} [0] Date string|object
         * @param {string} [1] Date format / Moment method
         * @param {*} [2] Moment method params
         * @param {*} [3] Moment method params 1
         * @param {*} [4] Moment method params 2
         * @param {string|date} [date] Alternative date
         * @param {string} [format] Alternative format
         * @param {string} [input] Format to use to parse date
         * @param {string} [lang] Specific locale to use
         * @param {number|string} [type] Type of weekday (L|S|XS|number)
         * @param {boolean} [suffix]
         * @param {boolean} [utc]
         * @param {boolean} [local]
         * @param {string} [from]
         * @param {string} [unixfrom]
         * @param {string} [max]
         * @param {string} [min]
         * @param {string} [unixmax]
         * @param {string} [unixmin]
         * @param {string} [startOf]
         * @param {string} [endOf]
         * @param {number|string} [add]
         * @param {number|string} [subtract]
         * @param {number} [addparam] Value to use if add is number
         * @param {number} [subtractparam] Value to use if subtract is number
         * @param {number} [amount] Value to use if add|subtract are strings
         * @param {string} [diff]
         * @param {string} [unixdiff]
         * @param {string} [unitdiff] Value for Moment method params 1 if diff
         * @param {boolean} [nosuffix] Value for Moment method params 2 if diff
         *
         * @description  Outputs a date
         *
         * Current date
         *
         *     {{moment}}
         *
         * Specific date
         *
         *     {{moment d}}
         *     {{moment date=d}}
         *
         * Date format
         *
         *     {{moment d "YY, MMM dd"}}
         *     {{moment date=d format="DD/MM/YYYY"}}
         *     {{moment d unix=true}}
         *
         * Date input parsing
         *
         *     {{moment dinput input="DD-YYYY-MM"}}
         *
         * Date timezone
         *
         *     {{moment dstr utc=true}}
         *     {{moment dstr local=true}}
         *
         * Date units
         *
         *     {{moment d "millisecond"}}
         *     {{moment d "second"}}
         *     {{moment d "minute"}}
         *     {{moment d "hour"}}
         *     {{moment d "date"}}
         *     {{moment d "day"}}
         *     {{moment d "weekday"}}
         *     {{moment d "weekday" type="s"}}
         *     {{moment d "weekday" type="xs"}}
         *     {{moment d "weekday" type="number"}}
         *     {{moment d "isoweekday"}}
         *     {{moment d "dayofyear"}}
         *     {{moment d "week"}}
         *     {{moment d "isoweek"}}
         *     {{moment d "month"}}
         *     {{moment d "year"}}
         *     {{moment d "weekyear"}}
         *     {{moment d "isoweekyear"}}
         *
         * Date manipulation
         *
         *     {{moment d add="days" amount="7"}}
         *     {{moment d add="365" addparam="d"}}
         *     {{moment d subtract="days" amount="7"}}
         *     {{moment d subtract="365" subtractparam="d"}}
         *
         * Start and end of years
         *
         *     {{moment d startof="year"}}
         *     {{moment d endof="year"}}
         *
         * Date max/min
         *
         *     {{moment d max=dmax}}
         *     {{moment d min=dmin}}
         *
         * Date from now and specific dates
         *
         *     {{moment d "fromNow"}}
         *     {{moment d "from" dfrom}}
         *
         * Difference between dates
         *
         *     {{moment d diff=ddiff}}
         *
         * Date as calendar time
         *
         *     {{moment d "calendar"}}
         *
         * Date as strings
         *
         *     {{moment d "str"}}
         *     {{moment d "val"}}
         *     {{moment d "unix"}}
         *
         * Moment utils
         *
         *     {{moment d "daysinmonth"}}
         *     {{moment d "todate"}}
         *     {{moment d "array"}}
         *     {{moment d "isostring"}}
         *
         * Helper parameters map to those of Moment.js unless noted
         */
        Handlebars.registerHelper("moment", function() {
            var args = Array.prototype.slice.call(arguments),
                options = args.pop(),
                date = args.shift(),
                format = args.shift(),
                formatParams = args.shift(),
                formatParams1 = args.shift(),
                formatParams2 = args.shift();

            if (options.hash && options.hash.params) {
                options.hash = _.extend({}, options.hash.params, options.hash);
                delete options.hash.params;
            }
            var params = options.hash;
            if (!date) {
                date = params.date;
            }
            function marshallDate (date, unix) {
                if (typeof date === "string" && date.match(/^\d+(\.\d+){0,1}$/)) {
                    date = +date;
                }
                if (unix && typeof date === "number") {
                    date = date * 1000;
                }
                return date;
            }
            date = marshallDate(date, params.unix);
            var max = marshallDate(params.max, params.unixmax);
            var min = marshallDate(params.min, params.unixmin);

            if (!format) {
                format = params.format || params.fn;
            }
            if (momentFormatMap[format]) {
                format = momentFormatMap[format];
            }
            if (format === "weekday") {
                params.type = params.type ? params.type.toUpperCase() : null;
                if (params.type !== "NUMBER") {
                    if (weekdayMap[params.type]) {
                        format = weekdayMap[params.type];
                    } else {
                        format = weekdayMap.L;
                    }
                }
            }

            var ofMethod = "start";
            var ofType = params.startOf || params.startof;
            if (!ofType) {
                ofType = params.endOf || params.endof;
                if (ofType) {
                    ofMethod = "end";
                }
            }

            /*if (!formatParams) {
                formatParams = params.formatparams || params.fnparams;
                if (formatParams === undefined) {
                    if (params.suffix !== undefined) {
                        formatParams = params.suffix;
                    }
                }
            }*/

            var momentObj;

            if (moment.isMoment(date)) {
                momentObj = date.clone();
            } else {
                var momentFn = params.utc ? moment.utc : moment;
                momentObj = momentFn(date, params.input);
            }

            if (params.lang) {
                momentObj.lang(params.lang);
            }

            if (max) {
                momentObj = moment.max(max, momentObj);
            }
            if (min) {
                momentObj = moment.min(min, momentObj);
            }

            if (ofType) {
                momentObj = momentObj[ofMethod + "Of"](ofType);
            }

            if (params.nosuffix === undefined && params.suffix !== undefined) {
                params.nosuffix = !params.suffix;
            }

            if (params.from) {
                format = "from";
                formatParams = marshallDate(params.from, params.unixfrom);
            }
            if (format === "fromNow") {
                if (formatParams === undefined) {
                    formatParams = params.nosuffix;
                }
            }
            if (format === "from") {
                if (formatParams1 === undefined) {
                    formatParams1 = params.nosuffix;
                }
            }
            if (params.diff) {
                format = "diff";
                formatParams = marshallDate(params.diff, params.unixdiff);
            }
            if (format === "diff") {
                if (formatParams1 === undefined) {
                    formatParams1 = params.unitdiff;
                }
                if (formatParams2 === undefined) {
                    formatParams2 = params.nosuffix;
                }
            }

            function manipulateMoment (method) {
                var arg = params[method];
                if (arg) {
                    var argParam = params[method + "param"];
                    if (argParam === undefined) {
                        argParam = params.amount;
                    }
                    var args = arg;
                    if (argParam) {
                        var addNum = +arg;
                        args = {};
                        if (isNaN(addNum)) {
                            args[arg] = +argParam;
                        } else {
                            args[argParam] = addNum;
                        }
                    }
                    momentObj[method](args);
                }
            }
            manipulateMoment("add");
            manipulateMoment("subtract");

            if (params.local) {
                momentObj.local();
            } else if (params.utc) {
                momentObj.utc();
            }

            var momentOutput = momentObj[format] ? momentObj[format](formatParams, formatParams1, formatParams2) : momentObj.format(format);

            return momentOutput;
        });

        var durationMethodMap = {
            asmilliseconds: "asMilliseconds",
            asseconds: "asSeconds",
            asminutes: "asMinutes",
            ashours: "asHours",
            asdays: "asDays",
            asweeks: "asWeeks",
            asmonths: "asMonths",
            asyears: "asYears"
        };
        var durationGetArray = [
            "ms",
            "s",
            "m",
            "h",
            "d",
            "w",
            "M",
            "y"
        ];
        var durationGetMap = {};
        for (var i in durationGetArray) {
            durationGetMap[durationGetArray[i]] = true;
        }

        /**
         * @template duration
         * @block helper
         * @param {string} [duration] Length of duration
         * @param {string} [input] Unit of duration
         * @param {number} [add]
         * @param {number} [subtract]
         * @param {number} [addunit|addparam]
         * @param {number} [subtractunit|subtractparam]
         * @param {string} [as] Sets duration method to as
         * @param {string} [get] Sets duration method to get
         * @param {string} [humanize] Sets duration method to humanize
         * @param {boolean} [suffix=false]
         *
         * @description  Outputs a duration
         *
         * Duration - implictly in milliseconds
         *
         *     {{duration d}}
         *
         * Duration with explicit input date unit type
         *
         *     {{duration d input="s"}}
         *
         * Amount of date units in duration
         *
         *     {{duration d "seconds"}}
         *     {{duration d "minutes"}}
         *     {{duration d "years"}}
         *     {{duration d get="seconds"}}
         *     {{duration d "s"}}
         *
         * Duration as date units
         *
         *     {{duration d "asseconds"}}
         *     {{duration d "asminutes"}}
         *     {{duration d "asyears"}}
         *     {{duration d as="seconds"}}
         *
         * Humanize duration output
         *
         *     {{duration d "humanize"}}
         *     {{duration d "humanize" true}}
         *     {{duration d suffix=true}}
         *
         * Manipulate durations
         *
         *     {{duration d add=damount as="milliseconds"}}
         *     {{duration d subtract=damount as="seconds"}}
         *     {{duration d subtract=damount as="days"}}
         */
        Handlebars.registerHelper("duration", function() {
            var args = Array.prototype.slice.call(arguments),
                options = args.pop(),
                duration = args.shift(),
                method = args.shift(),
                methodArg = args.shift();

            if (options.hash && options.hash.params) {
                options.hash = _.extend({}, options.hash.params, options.hash);
                delete options.hash.params;
            }
            var params = options.hash;
            if (!duration) {
                duration = params.duration;
            }
            if (typeof duration === "string" && duration.match(/^\d+$/)) {
                duration = +duration;
            }

            var durationObj = moment.duration(duration, params.input);

            function manipulateDuration (method) {
                var arg = params[method];
                if (arg) {
                    if (!isNaN(+arg)) {
                        arg = +arg;
                    }
                    var argParam = params[method + "unit"];
                    if (argParam === undefined) {
                        argParam = params[method + "param"];
                    }
                    durationObj[method](arg, argParam);
                }
            }
            manipulateDuration("add");
            manipulateDuration("subtract");

            if (!method) {
                method = params.method;
            }
            if (durationGetMap[method]) {
                methodArg = method;
                method = "get";
            }
            if (durationMethodMap[method]) {
                method = durationMethodMap[method];
            }
            if (params.as) {
                method = "as";
                methodArg = params.as;
            } else if (params.get) {
                method = "get";
                methodArg = params.get;
            }

            if (!durationObj[method]) {
                method = "humanize";
            }

            if (method === "humanize") {
                if (methodArg === undefined) {
                    methodArg = params.suffix;
                }
            }

            return durationObj[method](methodArg);
        });
    };

    var external = {
        /**
         * @method registerHelpers
         * @static
         * @param {object} hbars Handlebars instance
         * @description Register MomentHelper helpers with Handlebars
         *
         * - {@link template:moment}
         * - {@link template:duration}
         */
        registerHelpers: function (hbars) {
            MomentHelpers(hbars);
        }
    };

    return external;

}));<commit_msg>Added window checking for naive browser compatibility as per @MaffooBristol’s suggestion in https://github.com/solidgoldpig/handlebars.moment/issues/3<commit_after>(function (moduleFactory) {
    if (typeof exports === "object") {
        module.exports = moduleFactory(require("lodash"), require("moment"));
    } else if (typeof define === "function" && define.amd) {
        define(["lodash", "moment"], moduleFactory);
    } else if (typeof window !== 'undefined' && window != null) {
        window.HandlebarsMoment = moduleFactory(_, moment);
    }
}(function (_, moment) {
/**
 * @module handlebars%moment
 * @description  Helpers providing [Moment.js](http://momentjs.com) functionality
 *
 *     var Handlebars = require("handlebars");
 *     var MomentHelper = require("handlebars.moment");
 *     MomentHelper.registerHelpers(Handlebars);
 *
 * @returns {object} MomentHelper instance
 */

    var MomentHelpers = function (Handlebars) {
        var momentFormatMap = {
            dates: "date",
            months: "month",
            years: "year",
            isoweekday: "isoWeekday",
            dayofyear: "dayOfYear",
            isoweek: "isoWeek",
            isoweeks: "isoWeek",
            weekyear: "weekYear",
            isoweekyear: "isoWeekYear",
            zoneabbr: "zoneAbbr",
            zonename: "zoneName",
            tostring: "toString",
            string: "toString",
            str: "toString",
            valueof: "valueOf",
            value: "valueOf",
            val: "valueOf",
            fromnow: "fromNow",
            daysinmonth: "daysInMonth",
            todate: "toDate",
            toarray: "toArray",
            array: "toArray",
            tojson: "toJSON",
            json: "toJSON",
            toisostring: "toISOString",
            isostring: "toISOString"
        };
        var weekdayMap = {
            L: "dddd",
            S: "ddd",
            XS: "dd"
        };

        /**
         * @template moment
         * @block helper
         * @param {string|date} [0] Date string|object
         * @param {string} [1] Date format / Moment method
         * @param {*} [2] Moment method params
         * @param {*} [3] Moment method params 1
         * @param {*} [4] Moment method params 2
         * @param {string|date} [date] Alternative date
         * @param {string} [format] Alternative format
         * @param {string} [input] Format to use to parse date
         * @param {string} [lang] Specific locale to use
         * @param {number|string} [type] Type of weekday (L|S|XS|number)
         * @param {boolean} [suffix]
         * @param {boolean} [utc]
         * @param {boolean} [local]
         * @param {string} [from]
         * @param {string} [unixfrom]
         * @param {string} [max]
         * @param {string} [min]
         * @param {string} [unixmax]
         * @param {string} [unixmin]
         * @param {string} [startOf]
         * @param {string} [endOf]
         * @param {number|string} [add]
         * @param {number|string} [subtract]
         * @param {number} [addparam] Value to use if add is number
         * @param {number} [subtractparam] Value to use if subtract is number
         * @param {number} [amount] Value to use if add|subtract are strings
         * @param {string} [diff]
         * @param {string} [unixdiff]
         * @param {string} [unitdiff] Value for Moment method params 1 if diff
         * @param {boolean} [nosuffix] Value for Moment method params 2 if diff
         *
         * @description  Outputs a date
         *
         * Current date
         *
         *     {{moment}}
         *
         * Specific date
         *
         *     {{moment d}}
         *     {{moment date=d}}
         *
         * Date format
         *
         *     {{moment d "YY, MMM dd"}}
         *     {{moment date=d format="DD/MM/YYYY"}}
         *     {{moment d unix=true}}
         *
         * Date input parsing
         *
         *     {{moment dinput input="DD-YYYY-MM"}}
         *
         * Date timezone
         *
         *     {{moment dstr utc=true}}
         *     {{moment dstr local=true}}
         *
         * Date units
         *
         *     {{moment d "millisecond"}}
         *     {{moment d "second"}}
         *     {{moment d "minute"}}
         *     {{moment d "hour"}}
         *     {{moment d "date"}}
         *     {{moment d "day"}}
         *     {{moment d "weekday"}}
         *     {{moment d "weekday" type="s"}}
         *     {{moment d "weekday" type="xs"}}
         *     {{moment d "weekday" type="number"}}
         *     {{moment d "isoweekday"}}
         *     {{moment d "dayofyear"}}
         *     {{moment d "week"}}
         *     {{moment d "isoweek"}}
         *     {{moment d "month"}}
         *     {{moment d "year"}}
         *     {{moment d "weekyear"}}
         *     {{moment d "isoweekyear"}}
         *
         * Date manipulation
         *
         *     {{moment d add="days" amount="7"}}
         *     {{moment d add="365" addparam="d"}}
         *     {{moment d subtract="days" amount="7"}}
         *     {{moment d subtract="365" subtractparam="d"}}
         *
         * Start and end of years
         *
         *     {{moment d startof="year"}}
         *     {{moment d endof="year"}}
         *
         * Date max/min
         *
         *     {{moment d max=dmax}}
         *     {{moment d min=dmin}}
         *
         * Date from now and specific dates
         *
         *     {{moment d "fromNow"}}
         *     {{moment d "from" dfrom}}
         *
         * Difference between dates
         *
         *     {{moment d diff=ddiff}}
         *
         * Date as calendar time
         *
         *     {{moment d "calendar"}}
         *
         * Date as strings
         *
         *     {{moment d "str"}}
         *     {{moment d "val"}}
         *     {{moment d "unix"}}
         *
         * Moment utils
         *
         *     {{moment d "daysinmonth"}}
         *     {{moment d "todate"}}
         *     {{moment d "array"}}
         *     {{moment d "isostring"}}
         *
         * Helper parameters map to those of Moment.js unless noted
         */
        Handlebars.registerHelper("moment", function() {
            var args = Array.prototype.slice.call(arguments),
                options = args.pop(),
                date = args.shift(),
                format = args.shift(),
                formatParams = args.shift(),
                formatParams1 = args.shift(),
                formatParams2 = args.shift();

            if (options.hash && options.hash.params) {
                options.hash = _.extend({}, options.hash.params, options.hash);
                delete options.hash.params;
            }
            var params = options.hash;
            if (!date) {
                date = params.date;
            }
            function marshallDate (date, unix) {
                if (typeof date === "string" && date.match(/^\d+(\.\d+){0,1}$/)) {
                    date = +date;
                }
                if (unix && typeof date === "number") {
                    date = date * 1000;
                }
                return date;
            }
            date = marshallDate(date, params.unix);
            var max = marshallDate(params.max, params.unixmax);
            var min = marshallDate(params.min, params.unixmin);

            if (!format) {
                format = params.format || params.fn;
            }
            if (momentFormatMap[format]) {
                format = momentFormatMap[format];
            }
            if (format === "weekday") {
                params.type = params.type ? params.type.toUpperCase() : null;
                if (params.type !== "NUMBER") {
                    if (weekdayMap[params.type]) {
                        format = weekdayMap[params.type];
                    } else {
                        format = weekdayMap.L;
                    }
                }
            }

            var ofMethod = "start";
            var ofType = params.startOf || params.startof;
            if (!ofType) {
                ofType = params.endOf || params.endof;
                if (ofType) {
                    ofMethod = "end";
                }
            }

            /*if (!formatParams) {
                formatParams = params.formatparams || params.fnparams;
                if (formatParams === undefined) {
                    if (params.suffix !== undefined) {
                        formatParams = params.suffix;
                    }
                }
            }*/

            var momentObj;

            if (moment.isMoment(date)) {
                momentObj = date.clone();
            } else {
                var momentFn = params.utc ? moment.utc : moment;
                momentObj = momentFn(date, params.input);
            }

            if (params.lang) {
                momentObj.lang(params.lang);
            }

            if (max) {
                momentObj = moment.max(max, momentObj);
            }
            if (min) {
                momentObj = moment.min(min, momentObj);
            }

            if (ofType) {
                momentObj = momentObj[ofMethod + "Of"](ofType);
            }

            if (params.nosuffix === undefined && params.suffix !== undefined) {
                params.nosuffix = !params.suffix;
            }

            if (params.from) {
                format = "from";
                formatParams = marshallDate(params.from, params.unixfrom);
            }
            if (format === "fromNow") {
                if (formatParams === undefined) {
                    formatParams = params.nosuffix;
                }
            }
            if (format === "from") {
                if (formatParams1 === undefined) {
                    formatParams1 = params.nosuffix;
                }
            }
            if (params.diff) {
                format = "diff";
                formatParams = marshallDate(params.diff, params.unixdiff);
            }
            if (format === "diff") {
                if (formatParams1 === undefined) {
                    formatParams1 = params.unitdiff;
                }
                if (formatParams2 === undefined) {
                    formatParams2 = params.nosuffix;
                }
            }

            function manipulateMoment (method) {
                var arg = params[method];
                if (arg) {
                    var argParam = params[method + "param"];
                    if (argParam === undefined) {
                        argParam = params.amount;
                    }
                    var args = arg;
                    if (argParam) {
                        var addNum = +arg;
                        args = {};
                        if (isNaN(addNum)) {
                            args[arg] = +argParam;
                        } else {
                            args[argParam] = addNum;
                        }
                    }
                    momentObj[method](args);
                }
            }
            manipulateMoment("add");
            manipulateMoment("subtract");

            if (params.local) {
                momentObj.local();
            } else if (params.utc) {
                momentObj.utc();
            }

            var momentOutput = momentObj[format] ? momentObj[format](formatParams, formatParams1, formatParams2) : momentObj.format(format);

            return momentOutput;
        });

        var durationMethodMap = {
            asmilliseconds: "asMilliseconds",
            asseconds: "asSeconds",
            asminutes: "asMinutes",
            ashours: "asHours",
            asdays: "asDays",
            asweeks: "asWeeks",
            asmonths: "asMonths",
            asyears: "asYears"
        };
        var durationGetArray = [
            "ms",
            "s",
            "m",
            "h",
            "d",
            "w",
            "M",
            "y"
        ];
        var durationGetMap = {};
        for (var i in durationGetArray) {
            durationGetMap[durationGetArray[i]] = true;
        }

        /**
         * @template duration
         * @block helper
         * @param {string} [duration] Length of duration
         * @param {string} [input] Unit of duration
         * @param {number} [add]
         * @param {number} [subtract]
         * @param {number} [addunit|addparam]
         * @param {number} [subtractunit|subtractparam]
         * @param {string} [as] Sets duration method to as
         * @param {string} [get] Sets duration method to get
         * @param {string} [humanize] Sets duration method to humanize
         * @param {boolean} [suffix=false]
         *
         * @description  Outputs a duration
         *
         * Duration - implictly in milliseconds
         *
         *     {{duration d}}
         *
         * Duration with explicit input date unit type
         *
         *     {{duration d input="s"}}
         *
         * Amount of date units in duration
         *
         *     {{duration d "seconds"}}
         *     {{duration d "minutes"}}
         *     {{duration d "years"}}
         *     {{duration d get="seconds"}}
         *     {{duration d "s"}}
         *
         * Duration as date units
         *
         *     {{duration d "asseconds"}}
         *     {{duration d "asminutes"}}
         *     {{duration d "asyears"}}
         *     {{duration d as="seconds"}}
         *
         * Humanize duration output
         *
         *     {{duration d "humanize"}}
         *     {{duration d "humanize" true}}
         *     {{duration d suffix=true}}
         *
         * Manipulate durations
         *
         *     {{duration d add=damount as="milliseconds"}}
         *     {{duration d subtract=damount as="seconds"}}
         *     {{duration d subtract=damount as="days"}}
         */
        Handlebars.registerHelper("duration", function() {
            var args = Array.prototype.slice.call(arguments),
                options = args.pop(),
                duration = args.shift(),
                method = args.shift(),
                methodArg = args.shift();

            if (options.hash && options.hash.params) {
                options.hash = _.extend({}, options.hash.params, options.hash);
                delete options.hash.params;
            }
            var params = options.hash;
            if (!duration) {
                duration = params.duration;
            }
            if (typeof duration === "string" && duration.match(/^\d+$/)) {
                duration = +duration;
            }

            var durationObj = moment.duration(duration, params.input);

            function manipulateDuration (method) {
                var arg = params[method];
                if (arg) {
                    if (!isNaN(+arg)) {
                        arg = +arg;
                    }
                    var argParam = params[method + "unit"];
                    if (argParam === undefined) {
                        argParam = params[method + "param"];
                    }
                    durationObj[method](arg, argParam);
                }
            }
            manipulateDuration("add");
            manipulateDuration("subtract");

            if (!method) {
                method = params.method;
            }
            if (durationGetMap[method]) {
                methodArg = method;
                method = "get";
            }
            if (durationMethodMap[method]) {
                method = durationMethodMap[method];
            }
            if (params.as) {
                method = "as";
                methodArg = params.as;
            } else if (params.get) {
                method = "get";
                methodArg = params.get;
            }

            if (!durationObj[method]) {
                method = "humanize";
            }

            if (method === "humanize") {
                if (methodArg === undefined) {
                    methodArg = params.suffix;
                }
            }

            return durationObj[method](methodArg);
        });
    };

    var external = {
        /**
         * @method registerHelpers
         * @static
         * @param {object} hbars Handlebars instance
         * @description Register MomentHelper helpers with Handlebars
         *
         * - {@link template:moment}
         * - {@link template:duration}
         */
        registerHelpers: function (hbars) {
            MomentHelpers(hbars);
        }
    };

    return external;

}));<|endoftext|>


<commit_before>var fs = require("fs"),
    debug = require("debug"),

    mime = require("mime"),
    crypto = require("crypto"),
    HttpError = require("http_error"),
    filePath = require("file_path");

function normalizeRoot(root) {
    if (!root || root === ".") return "/";
    if (root[0] === ".") root = root.slice(1);
    if (root[0] !== "/") root = "/" + root;
    if (root[root.length - 1] !== "/") root += "/";
    return root;
}

function etagFn(buffer) {

    return crypto.createHash("md5").update(buffer).digest("base64");
}

function StaticServe(options) {
    options || (options = {});

    this.root = normalizeRoot(options.root || "assets");
    this.rootLength = this.root.length;

    this.directory = options.directory || "./assets";
    this.fullDirectory = filePath.isAbsolute(this.directory) ? this.directory : filePath.join(process.cwd(), this.directory);

    this.index = options.index != null ? options.index : "index.html";

    this.debug = debug("Static Serve");

    this.etagFn = typeof(options.etagFn) === "function" ? options.etagFn : etagFn;

    this.options = {
        maxAge: options.maxAge || 86400000,
        fallback: options.fallback != null ? !!options.fallback : false,
        etag: options.etag != null ? !!options.etag : true,
        lastModified: options.lastModified != null ? !!options.lastModified : true
    };
}

StaticServe.express = function(options) {
    var staticServe = new StaticServe(options);

    return function(req, res, next) {

        staticServe.middleware(req, res, next);
    };
};

StaticServe.connect = StaticServe.express;

StaticServe.prototype.middleware = function(req, res, next) {
    var _this = this,
        method = req.method,
        pathname = req.pathname,
        relativeName,
        fileName;

    if (method !== "GET" && method !== "HEAD") {
        next();
        return;
    }
    if (pathname.indexOf(this.root) !== 0) {
        next();
        return;
    }

    relativeName = pathname.substring(this.rootLength);
    fileName = filePath.join(this.fullDirectory, relativeName);

    fs.stat(fileName, function(err, stat) {
        if (err) {
            next(new HttpError(404, err));
            return;
        }
        if (!stat) {
            next();
            return;
        }

        if (stat.isDirectory()) {
            if (!_this.index) {
                next();
                return;
            }

            relativeName = _this.index;
            fileName = filePath.join(fileName, relativeName);

            fs.stat(fileName, function(err, stat) {
                if (err || !stat) {
                    next(new HttpError(404, err));
                    return;
                }

                _this.send(res, relativeName, fileName, stat, next);
            });
        } else {
            _this.send(res, relativeName, fileName, stat, next);
        }
    });
};

StaticServe.prototype.send = function(res, relativeName, fileName, stat, next) {
    var isHead = res.request.method === "HEAD",
        options = this.options,
        ext = filePath.ext(fileName),
        type = mime.lookUpType(ext, options.fallback),
        modified, stream;

    if (type) {
        modified = res.modified(stat.mtime);

        res.contentType = type;
        res.statusCode = modified ? 200 : 304;

        if (options.maxAge && !res.getHeader("Cache-Control")) res.setHeader("Cache-Control", "public, max-age=" + (options.maxAge / 1000));
        if (modified && options.lastModified && !res.getHeader("Last-Modified")) res.setHeader("Last-Modified", stat.mtime.toUTCString());
        if (options.etag && !res.getHeader("ETag")) res.setHeader("ETag", 'W/"' + this.etagFn(this.etag(fileName, stat)) + '"');
        if (!res.getHeader("Date")) res.setHeader("Date", new Date().toUTCString());

        if (isHead) {
            this.debug("HEAD " + relativeName + " as " + type);

            res.setHeader("Content-Length", 0);
            res.end();
            next();
        } else {
            this.debug(relativeName + " as " + type);

            res.setHeader("Content-Length", stat.size);

            stream = fs.createReadStream(fileName);

            stream.on("error", function(err) {
                if (res.headersSent) {
                    console.log(err.stack);
                    stream.destroy();
                }
            });

            stream.on("open", function() {
                stream.pipe(res);
            });
        }
    } else {
        next(new HttpError(415));
    }

    return this;
};

StaticServe.prototype.etag = function(fileName, stat) {

    return String(stat.mtime.getTime()) + ':' + String(stat.size) + ':' + fileName;
};

module.exports = StaticServe;
<commit_msg>updates<commit_after>var fs = require("fs"),
    debug = require("debug"),

    mime = require("mime"),
    crypto = require("crypto"),
    HttpError = require("http_error"),
    filePath = require("file_path");

function normalizeRoot(root) {
    if (!root || root === ".") return "/";
    if (root[0] === ".") root = root.slice(1);
    if (root[0] !== "/") root = "/" + root;
    if (root[root.length - 1] !== "/") root += "/";
    return root;
}

function etagFn(buffer) {

    return crypto.createHash("md5").update(buffer).digest("base64");
}

function StaticServe(options) {
    options || (options = {});

    this.root = normalizeRoot(options.root || "assets");
    this.rootLength = this.root.length;

    this.directory = options.directory || "./assets";
    this.fullDirectory = filePath.isAbsolute(this.directory) ? this.directory : filePath.join(process.cwd(), this.directory);

    this.index = options.index != null ? options.index : "index.html";

    this.debug = debug("Static Serve");

    this.etagFn = typeof(options.etagFn) === "function" ? options.etagFn : etagFn;

    this.options = {
        maxAge: options.maxAge || 86400000,
        fallback: options.fallback != null ? !!options.fallback : false,
        etag: options.etag != null ? !!options.etag : true,
        lastModified: options.lastModified != null ? !!options.lastModified : true
    };
}

StaticServe.express = function(options) {
    var staticServe = new StaticServe(options);

    return function(req, res, next) {

        staticServe.middleware(req, res, next);
    };
};

StaticServe.connect = StaticServe.express;

StaticServe.prototype.middleware = function(req, res, next) {
    var _this = this,
        method = req.method,
        pathname = req.pathname,
        relativeName,
        fileName;

    if (method !== "GET" && method !== "HEAD") {
        next();
        return;
    }
    if (pathname.indexOf(this.root) !== 0) {
        next();
        return;
    }

    relativeName = pathname.substring(this.rootLength);
    fileName = filePath.join(this.fullDirectory, relativeName);

    fs.stat(fileName, function(err, stat) {
        if (err) {
            next(new HttpError(404, err));
            return;
        }
        if (!stat) {
            next();
            return;
        }

        if (stat.isDirectory()) {
            if (!_this.index) {
                next();
                return;
            }

            relativeName = _this.index;
            fileName = filePath.join(fileName, relativeName);

            fs.stat(fileName, function(err, stat) {
                if (err || !stat) {
                    next(new HttpError(404, err));
                    return;
                }

                _this.send(res, relativeName, fileName, stat, next);
            });
        } else {
            _this.send(res, relativeName, fileName, stat, next);
        }
    });
};

StaticServe.prototype.send = function(res, relativeName, fileName, stat, next) {
    var isHead = res.request.method === "HEAD",
        options = this.options,
        ext = filePath.ext(fileName),
        type = mime.lookUpType(ext, options.fallback),
        modified, stream;

    if (type) {
        modified = res.modified(stat.mtime);

        res.contentType = type;
        res.statusCode = modified ? 200 : 304;

        if (options.maxAge && !res.getHeader("Cache-Control")) {
            res.setHeader("Cache-Control", "public, max-age=" + (options.maxAge / 1000));
        }
        if (modified && options.lastModified && !res.getHeader("Last-Modified")) {
            res.setHeader("Last-Modified", stat.mtime.toUTCString());
        }
        if (options.etag && !res.getHeader("ETag")) {
            res.setHeader("ETag", 'W/"' + this.etagFn(this.etag(fileName, stat)) + '"');
        }
        if (!res.getHeader("Date")) {
            res.setHeader("Date", new Date().toUTCString());
        }

        if (isHead) {
            this.debug("HEAD " + relativeName + " as " + type);

            res.setHeader("Content-Length", 0);
            res.end();
            next();
        } else {
            this.debug(relativeName + " as " + type);

            res.setHeader("Content-Length", stat.size);

            stream = fs.createReadStream(fileName);

            stream.on("error", function(err) {
                if (res.headersSent) {
                    console.log(err.stack);
                    stream.destroy();
                }
            });

            stream.on("open", function() {
                stream.pipe(res);
            });
        }
    } else {
        next(new HttpError(415));
    }

    return this;
};

StaticServe.prototype.etag = function(fileName, stat) {

    return String(stat.mtime.getTime()) + ':' + String(stat.size) + ':' + fileName;
};

module.exports = StaticServe;
<|endoftext|>


<commit_before>import { Template } from 'meteor/templating';
import { Tracker } from 'meteor/tracker';
import { _ } from 'meteor/erasaur:meteor-lodash';
import { Roles } from 'meteor/alanning:roles';
import SimpleSchema from 'simpl-schema';
import { updateMethod } from '../../../api/base/BaseCollection.methods';
import { ROLE } from '../../../api/role/Role.js';
import * as FormUtils from './form-fields/form-field-utilities.js';
import { MentorQuestions } from '../../../api/mentor/MentorQuestionCollection';
import { Slugs } from '../../../api/slug/SlugCollection';

const updateSchema = new SimpleSchema({
  question: String,
  user: String,
  slug: String,
  moderated: String,
  visible: String,
  moderatorComments: { type: String, optional: true },
}, { tracker: Tracker });

Template.Update_Mentor_Question_Widget.onCreated(function onCreated() {
  FormUtils.setupFormWidget(this, updateSchema);
});

Template.Update_Mentor_Question_Widget.helpers({
  students() {
    const mentors = Roles.getUsersInRole([ROLE.STUDENT]).fetch();
    const sorted = _.sortBy(mentors, 'lastName');
    return sorted;
  },
  mentorQuestion() {
    const ma = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return ma;
  },
  questions() {
    const questions = MentorQuestions.find({}, { sort: { question: 1 } }).fetch();
    return questions;
  },
  slug() {
    const mentorQuestion = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return Slugs.findDoc(mentorQuestion.slugID).name;
  },
  trueValueModerated() {
    const course = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return course.moderated;
  },
  falseValueModerated() {
    const course = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return !course.moderated;
  },
  trueValueVisible() {
    const course = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return course.visible;
  },
  falseValueVisible() {
    const course = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return !course.visible;
  },

});

Template.Update_Mentor_Question_Widget.events({
  submit(event, instance) {
    event.preventDefault();
    const updateData = FormUtils.getSchemaDataFromEvent(updateSchema, event);
    console.log(updateData);
    instance.context.reset();
    updateSchema.clean(updateData, { mutate: true });
    instance.context.validate(updateData);
    if (instance.context.isValid()) {
      FormUtils.renameKey(updateData, 'user', 'student');
      updateData.moderated = (updateData.moderated === 'true');
      updateData.visible = (updateData.visible === 'true');
      updateData.id = instance.data.updateID.get();
      console.log(_.hasIn(updateData, 'moderatorComments'));
      if (!_.has(updateData, 'moderatorComments')) {
        console.log('nulling');
        updateData.moderatorComments = ' ';
      }
      console.log(updateData);
      updateMethod.call({ collectionName: 'MentorQuestionCollection', updateData }, (error) => {
        if (error) {
          FormUtils.indicateError(instance, error);
        } else {
          FormUtils.indicateSuccess(instance, event);
        }
      });
    } else {
      FormUtils.indicateError(instance);
    }
  },
  'click .jsCancel': FormUtils.processCancelButtonClick,
});
<commit_msg>removed console.log<commit_after>import { Template } from 'meteor/templating';
import { Tracker } from 'meteor/tracker';
import { _ } from 'meteor/erasaur:meteor-lodash';
import { Roles } from 'meteor/alanning:roles';
import SimpleSchema from 'simpl-schema';
import { updateMethod } from '../../../api/base/BaseCollection.methods';
import { ROLE } from '../../../api/role/Role.js';
import * as FormUtils from './form-fields/form-field-utilities.js';
import { MentorQuestions } from '../../../api/mentor/MentorQuestionCollection';
import { Slugs } from '../../../api/slug/SlugCollection';

const updateSchema = new SimpleSchema({
  question: String,
  user: String,
  slug: String,
  moderated: String,
  visible: String,
  moderatorComments: { type: String, optional: true },
}, { tracker: Tracker });

Template.Update_Mentor_Question_Widget.onCreated(function onCreated() {
  FormUtils.setupFormWidget(this, updateSchema);
});

Template.Update_Mentor_Question_Widget.helpers({
  students() {
    const mentors = Roles.getUsersInRole([ROLE.STUDENT]).fetch();
    const sorted = _.sortBy(mentors, 'lastName');
    return sorted;
  },
  mentorQuestion() {
    const ma = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return ma;
  },
  questions() {
    const questions = MentorQuestions.find({}, { sort: { question: 1 } }).fetch();
    return questions;
  },
  slug() {
    const mentorQuestion = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return Slugs.findDoc(mentorQuestion.slugID).name;
  },
  trueValueModerated() {
    const course = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return course.moderated;
  },
  falseValueModerated() {
    const course = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return !course.moderated;
  },
  trueValueVisible() {
    const course = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return course.visible;
  },
  falseValueVisible() {
    const course = MentorQuestions.findDoc(Template.currentData().updateID.get());
    return !course.visible;
  },

});

Template.Update_Mentor_Question_Widget.events({
  submit(event, instance) {
    event.preventDefault();
    const updateData = FormUtils.getSchemaDataFromEvent(updateSchema, event);
    instance.context.reset();
    updateSchema.clean(updateData, { mutate: true });
    instance.context.validate(updateData);
    if (instance.context.isValid()) {
      FormUtils.renameKey(updateData, 'user', 'student');
      updateData.moderated = (updateData.moderated === 'true');
      updateData.visible = (updateData.visible === 'true');
      updateData.id = instance.data.updateID.get();
      if (!_.has(updateData, 'moderatorComments')) {
        updateData.moderatorComments = ' ';
      }
      updateMethod.call({ collectionName: 'MentorQuestionCollection', updateData }, (error) => {
        if (error) {
          FormUtils.indicateError(instance, error);
        } else {
          FormUtils.indicateSuccess(instance, event);
        }
      });
    } else {
      FormUtils.indicateError(instance);
    }
  },
  'click .jsCancel': FormUtils.processCancelButtonClick,
});
<|endoftext|>


<commit_before>
var fs = require('fs'),
    Path = require('path'),
    scripts;

scripts = [
    'pokeblender.js',
    'nugme.coffee',
    'mta.coffee',
    "redis-brain.coffee", "tweet.coffee", "shipit.coffee", "brewerydb.coffee", "applause.coffee", "ambush.coffee", "dealwithit.coffee", "decide.coffee", "futurama.coffee", "fortune.coffee", "hashing.coffee", "github-activity.coffee", "github-commit-link.coffee", "github-commits.coffee", "github-pulls.coffee", "http-say.coffee", "isup.coffee", "jenkins-notifier.coffee", "phpdoc.coffee", "scotch.coffee", "sudo.coffee", "swanson.coffee", "wikipedia.coffee", "wunderground.coffee", "xkcd.coffee", 'spot.coffee'
];

module.exports = function (robot) {
    var path = Path.resolve(__dirname, 'scripts');
    fs.exists(path, function (exists) {
        if (exists) {
            scripts.forEach(function (file) {
                robot.loadFile(path, file);
            });
        }
    });
};
<commit_msg>removed extra/unmodified scripts<commit_after>
var fs = require('fs'),
    Path = require('path'),
    scripts;

scripts = [
    'pokeblender.js',
    'nugme.coffee',
    'mta.coffee',
    'spot.coffee'
];

module.exports = function (robot) {
    var path = Path.resolve(__dirname, 'scripts');
    fs.exists(path, function (exists) {
        if (exists) {
            scripts.forEach(function (file) {
                robot.loadFile(path, file);
            });
        }
    });
};
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import { FlatList } from 'react-native';

export class InvertibleFlatList extends PureComponent {
    render() {
        const {inverted, ...forwardedProps} = this.props;

        // If not inverted, render as an ordinary FlatList
        if (!inverted) {
            return (
                <FlatList
                    {...forwardedProps}
                />
            )
        }

        this.inversionDirection = this.props.horizontal ? styles.horizontal : styles.vertical;
        return (
            <View style={this.inversionDirection}>
                <FlatList
                    ref={this._setFlatListRef}
                    {...forwardedProps}
                    renderItem={this._renderItem}
                />
            </View>
        );
    }

    _setFlatListRef = (flatListRef) => {
        this.flatListRef = flatListRef
    }

    _renderItem = (info) => {
        return (
            <View style={this.inversionDirection}>
                {this.props.renderItem(info)}
            </View>
        );
    }

    getMetrics = () => {
        return this.flatListRef.getMetrics();
    }

    scrollToEnd = (params) => {
        this.flatListRef.scrollToEnd(params);
    }

    scrollToIndex = (params) => {
        this.flatListRef.scrollToIndex(params);
    }

    scrollToItem = (params) => {
        this.flatListRef.scrollToItem(params);
    }

    scrollToOffset = (params) => {
        this.flatListRef.scrollToOffset(params);
    }

    recordInteraction = () => {
        this.flatListRef.recordInteraction();
    }
}

const styles = StyleSheet.create({
    vertical: {
        transform: [{ scaleY: -1 }],
    },
    horizontal: {
        transform: [{ scaleX: -1 }],
    },
});
<commit_msg>Add missing imports<commit_after>import React, { PureComponent } from 'react';
import { FlatList, StyleSheet, View } from 'react-native';

export class InvertibleFlatList extends PureComponent {
    render() {
        const {inverted, ...forwardedProps} = this.props;

        // If not inverted, render as an ordinary FlatList
        if (!inverted) {
            return (
                <FlatList
                    {...forwardedProps}
                />
            )
        }

        this.inversionDirection = this.props.horizontal ? styles.horizontal : styles.vertical;
        return (
            <View style={[styles.container, this.inversionDirection]}>
                <FlatList
                    ref={this._setFlatListRef}
                    {...forwardedProps}
                    renderItem={this._renderItem}
                />
            </View>
        );
    }

    _setFlatListRef = (flatListRef) => {
        this.flatListRef = flatListRef
    }

    _renderItem = (info) => {
        return (
            <View style={[styles.container, this.inversionDirection]}>
                {this.props.renderItem(info)}
            </View>
        );
    }

    getMetrics = () => {
        return this.flatListRef.getMetrics();
    }

    scrollToEnd = (params) => {
        this.flatListRef.scrollToEnd(params);
    }

    scrollToIndex = (params) => {
        this.flatListRef.scrollToIndex(params);
    }

    scrollToItem = (params) => {
        this.flatListRef.scrollToItem(params);
    }

    scrollToOffset = (params) => {
        this.flatListRef.scrollToOffset(params);
    }

    recordInteraction = () => {
        this.flatListRef.recordInteraction();
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    vertical: {
        transform: [{ scaleY: -1 }],
    },
    horizontal: {
        transform: [{ scaleX: -1 }],
    },
});
<|endoftext|>


<commit_before>function customAlerts(a, b){
    if (!a) {
        throw "Error: "+a+" must be a string.";
    }

    if (typeof a !== 'string') {
        throw "Error: "+a+" must be a string.";
    }

    else {
        window.addEventListener('load', function() {
            if (window.Notification && Notification.permission !== "granted") {
                Notification.requestPermission(function(status) {
                    if (Notification.permission !== status) {
                        Notification.permission = status;
                    }
                });
            }
        });

        function notifyAlerts(data, status, title) {
            var savedStr = localStorage.getItem("n") || "";
            var dirtyStr = "";
            var icon, text, aid;
            var alertsLength = data ? Object.keys(data).length : 0;

            if (Notification.permission === "granted" && alertsLength > 0) {
                for (var j = 0; j < alertsLength; j++){
                    var daid = data[j].alert_id;
                    dirtyStr += daid;
                }
                for (var i = 0; i < alertsLength; i++) {
                    var linkText = data[i].text;
                    var iconText = data[i].icon;
                    var url = data[i].primary_url;
                    var iconBegin = iconText.indexOf("http");
                    var iconEnd = iconText.indexOf("' border");
                    icon = iconText.substring(iconBegin, iconEnd) || null;
                    text = jQuery(linkText).text(); aid = data[i].alert_id;

                    if (savedStr.indexOf(aid) < 0) {
                        spawnNotification(title, text, icon, aid, url);
                    }
                }

                localStorage.setItem("n",dirtyStr);
            }
        }

        function spawnNotification(title, text, icon, tag, url) {
            var options = {
                body: text,
                icon: icon,
                tag: tag
            };
            var n = new Notification(title, options);
            setTimeout(n.close.bind(n), 10000);
            n.onclick = function() {
                window.open(url, '_blank');
            };
        }

        var title = a;
        var interval = (b && typeof b === 'number' && b > 15000) ? b : 15000;
        var options = {
            url: 'index.php?recent_alerts=1&js=1',
            dataType: 'json',
            success: function (data, status) {
                notifyAlerts(data, status, title);
            }
        };

        window.setInterval(function() {
            console.log('polling every '+interval+' milliseconds...');
            jQuery.ajax(options);
        }, interval);
    }
}<commit_msg>remove event listener out of conditional, condense exceptions<commit_after>window.addEventListener('load', function() {
    if (window.Notification && Notification.permission !== "granted") {
        Notification.requestPermission(function(status) {
            if (Notification.permission !== status) {
                Notification.permission = status;
            }
        });
    }
});

function customAlerts(a, b){
    if (!a || typeof a !== 'string') {
        throw "Error: "+a+" must be a string.";
    }

    else {
        function notifyAlerts(data, status, title) {
            var savedStr = localStorage.getItem("n") || "";
            var dirtyStr = "";
            var icon, text, aid;
            var alertsLength = data ? Object.keys(data).length : 0;

            if (Notification.permission === "granted" && alertsLength > 0) {
                for (var j = 0; j < alertsLength; j++){
                    var daid = data[j].alert_id;
                    dirtyStr += daid;
                }
                for (var i = 0; i < alertsLength; i++) {
                    var linkText = data[i].text;
                    var iconText = data[i].icon;
                    var url = data[i].primary_url;
                    var iconBegin = iconText.indexOf("http");
                    var iconEnd = iconText.indexOf("' border");
                    icon = iconText.substring(iconBegin, iconEnd) || null;
                    text = jQuery(linkText).text(); aid = data[i].alert_id;

                    if (savedStr.indexOf(aid) < 0) {
                        spawnNotification(title, text, icon, aid, url);
                    }
                }

                localStorage.setItem("n",dirtyStr);
            }
        }

        function spawnNotification(title, text, icon, tag, url) {
            var options = {
                body: text,
                icon: icon,
                tag: tag
            };
            var n = new Notification(title, options);
            setTimeout(n.close.bind(n), 10000);
            n.onclick = function() {
                window.open(url, '_blank');
            };
        }

        var title = a;
        var interval = (b && typeof b === 'number' && b > 15000) ? b : 15000;
        var options = {
            url: 'index.php?recent_alerts=1&js=1',
            dataType: 'json',
            success: function (data, status) {
                notifyAlerts(data, status, title);
            }
        };

        window.setInterval(function() {
            console.log('polling every '+interval+' milliseconds...');
            jQuery.ajax(options);
        }, interval);
    }
}<|endoftext|>


<commit_before>import * as LogManager from 'aurelia-logging';

const logger = LogManager.getLogger('event-aggregator');

class Handler {
  constructor(messageType, callback){
    this.messageType = messageType;
    this.callback = callback;
  }

  handle(message){
    if(message instanceof this.messageType){
      executeHandler(() => this.callback.call(null, message));
    }
  }
}

function executeHandler(handler) {
  try {
    handler();
  } catch(e) {
    logger.error(e);
  }
}

export class EventAggregator {
  constructor(){
    this.eventLookup = {};
    this.messageHandlers = [];
  }

  publish(event: string | any, data?: any){
    var subscribers, i;

    if(typeof event === 'string'){
      subscribers = this.eventLookup[event];
      if(subscribers){
        subscribers = subscribers.slice();
        i = subscribers.length;

        while(i--) {
          executeHandler(() => subscribers[i](data, event));
        }
      }
    }else{
      subscribers = this.messageHandlers.slice();
      i = subscribers.length;

      while(i--) {
        subscribers[i].handle(event);
      }
    }
  }

  subscribe(event, callback){
    var subscribers, handler;

    if(typeof event === 'string'){
      subscribers = this.eventLookup[event] || (this.eventLookup[event] = []);

      subscribers.push(callback);

      return function(){
        var idx = subscribers.indexOf(callback);
        if (idx != -1) {
          subscribers.splice(idx, 1);
        }
      };
    }else{
      handler = new Handler(event, callback);
      subscribers = this.messageHandlers;

      subscribers.push(handler);

      return function(){
        var idx = subscribers.indexOf(handler);
        if (idx != -1) {
          subscribers.splice(idx, 1);
        }
      };
    }
  }

  subscribeOnce(event, callback){
    var sub = this.subscribe(event,function(data,event){
      sub();
      return callback(data,event);
    });
    return sub;
  }
}

export function includeEventsIn(obj){
  var ea = new EventAggregator();

  obj.subscribeOnce = function(event, callback){
    return ea.subscribeOnce(event, callback);
  };

  obj.subscribe = function(event, callback){
    return ea.subscribe(event, callback);
  };

  obj.publish = function(event, data){
    ea.publish(event, data);
  };

  return ea;
}

export function configure(config){
  config.instance(EventAggregator, includeEventsIn(config.aurelia));
}
<commit_msg>feat(all): add more type info<commit_after>import * as LogManager from 'aurelia-logging';

const logger = LogManager.getLogger('event-aggregator');

class Handler {
  constructor(messageType, callback){
    this.messageType = messageType;
    this.callback = callback;
  }

  handle(message){
    if(message instanceof this.messageType){
      executeHandler(() => this.callback.call(null, message));
    }
  }
}

function executeHandler(handler) {
  try {
    handler();
  } catch(e) {
    logger.error(e);
  }
}

export class EventAggregator {
  constructor(){
    this.eventLookup = {};
    this.messageHandlers = [];
  }

  publish(event: string | any, data?: any){
    var subscribers, i;

    if(typeof event === 'string'){
      subscribers = this.eventLookup[event];
      if(subscribers){
        subscribers = subscribers.slice();
        i = subscribers.length;

        while(i--) {
          executeHandler(() => subscribers[i](data, event));
        }
      }
    }else{
      subscribers = this.messageHandlers.slice();
      i = subscribers.length;

      while(i--) {
        subscribers[i].handle(event);
      }
    }
  }

  subscribe(event: string | Function, callback: Function): Function {
    var subscribers, handler;

    if(typeof event === 'string'){
      subscribers = this.eventLookup[event] || (this.eventLookup[event] = []);

      subscribers.push(callback);

      return function(){
        var idx = subscribers.indexOf(callback);
        if (idx != -1) {
          subscribers.splice(idx, 1);
        }
      };
    }else{
      handler = new Handler(event, callback);
      subscribers = this.messageHandlers;

      subscribers.push(handler);

      return function(){
        var idx = subscribers.indexOf(handler);
        if (idx != -1) {
          subscribers.splice(idx, 1);
        }
      };
    }
  }

  subscribeOnce(event: string | Function, callback: Function): Function {
    var sub = this.subscribe(event,function(data,event){
      sub();
      return callback(data,event);
    });
    return sub;
  }
}

export function includeEventsIn(obj: Object): EventAggregator {
  var ea = new EventAggregator();

  obj.subscribeOnce = function(event, callback){
    return ea.subscribeOnce(event, callback);
  };

  obj.subscribe = function(event, callback){
    return ea.subscribe(event, callback);
  };

  obj.publish = function(event, data){
    ea.publish(event, data);
  };

  return ea;
}

export function configure(config: Object): void {
  config.instance(EventAggregator, includeEventsIn(config.aurelia));
}
<|endoftext|>


<commit_before>/**
 * Copyright 2019, Google, Inc.
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

module.exports = function(session) {
  const Store = session.Store;

  class FirestoreStore extends Store {
    constructor(options) {
      options = options || {};
      super(options);
      this.ds = options.dataset;
      if (!this.ds) {
        throw new Error('No dataset provided to Firestore Session.');
      }
      this.kind = options.kind || 'Session';
    }

    get(sid, callback) {
      this.ds.get(this.ds.key([this.kind, sid]), (err, entity) => {
        if (err) {
          return callback(err);
        }
        if (!entity) {
          return callback();
        }

        let result;
        try {
          result = JSON.parse(entity.data);
        } catch (er) {
          return callback(er);
        }
        return callback(null, result);
      });
    }

    set(sid, sess, callback) {
      callback = callback || (() => {});
      let sessJson;

      try {
        sessJson = JSON.stringify(sess);
      } catch (err) {
        return callback(err);
      }

      this.ds.save(
        {
          key: this.ds.key([this.kind, sid]),
          data: [
            {
              name: 'data',
              value: sessJson,
              excludeFromIndexes: true,
            },
          ],
        },
        callback
      );
    }

    destroy(sid, fn) {
      this.ds.delete(this.ds.key([this.kind, sid]), fn);
    }
  }
  return FirestoreStore;
};
<commit_msg>Use same field name for sessions<commit_after>/**
 * Copyright 2019, Google, Inc.
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

module.exports = function(session) {
  const Store = session.Store;

  class FirestoreStore extends Store {
    constructor(options) {
      options = options || {};
      super(options);
      this.db = options.dataset;
      if (!this.db) {
        throw new Error('No dataset provided to Firestore Session.');
      }
      this.kind = options.kind || 'Session';
    }

    get(sid, callback) {
      this.db
        .collection(this.kind)
        .doc(sid)
        .get()
        .then(doc => {
          if (!doc.exists) {
            return callback();
          }

          try {
            const result = JSON.parse(doc.data().data);
            return callback(null, result);
          } catch (err) {
            return callback(err);
          }
        })
        .catch(err => callback(err));
    }

    set(sid, sess, callback) {
      callback = callback || (() => {});
      let sessJson;

      try {
        sessJson = JSON.stringify(sess);
      } catch (err) {
        return callback(err);
      }

      this.db
        .collection(this.kind)
        .doc(sid)
        .set({data: sessJson});
      callback();
    }

    destroy(sid, callback) {
      this.db
        .collection(this.kind)
        .doc(sid)
        .delete();
      callback();
    }
  }
  return FirestoreStore;
};
<|endoftext|>


<commit_before>// $(document).ready(function(){
//   setTimeout(function(){
//     $(".hormone").hide();
//   }, 1000);
//   $(".col6").on("click", function(){
//     $(this).children().show("slow", function(){

//     });
//     // $(this).find(".hormone").show()
//   });

// });

// // $(".col6").on("click", function(){alert("hi")})
// $(".col6").on("click", function(){$(this).find(".hormone").show()})

$(document).ready(function(){
  setTimeout(function(){
    $(".hormone").hide();
  }, 1000);
  $(".card").on("click", function(alert){
    $(this).find(".hormone").fadeIn()
  });

});
<commit_msg>add workign javascript<commit_after>

$(document).ready(function(){
  setTimeout(function(){
    $(".hormone").hide();
    $(".card").on("click", function(alert){
      $(this).find(".hormone").fadeIn()
    });
  }, 1000);

});
<|endoftext|>


<commit_before>import { resolve, relative, isAbsolute } from "path"
import { eachOfSeries } from "async"
import { camelCase } from "lodash"
import fileExists from "file-exists"
import meow from "meow"

import { rollup } from "rollup"
import relink from "rollup-plugin-relink"
import nodeResolve from "rollup-plugin-node-resolve"
import jsonPlugin from "rollup-plugin-json"
import yamlPlugin from "rollup-plugin-yaml"
import replacePlugin from "rollup-plugin-replace"

import getTranspilers from "./getTranspilers"
import getBanner from "./getBanner"

const CWD = process.cwd()
const PKG = require(resolve(CWD, "package.json"))

var cache

const cli = meow(`
  Usage
    $ prepublish-lib

  Options
    --entry-node      Entry file for NodeJS environment [default = auto]
    --entry-browser   Entry file for Browser environment [default = auto]

    --output-folder   Configure the output folder [default = auto]

    -t, --transpiler  Chose the transpiler/config to use. Either "react", "latest" or "buble". [default = latest]
    -x, --minified    Enabled minification of output files
    -m, --sourcemap   Create a source map file during processing

    -v, --verbose     Verbose output mode [default = false]
    -q, --quiet       Quiet output mode [default = false]
`, {
  default: {
    entryNode: null,
    entryBrowser: null,

    outputFolder: null,

    transpiler: "react",
    minified: false,
    sourcemap: true,

    verbose: false,
    quiet: false
  }
})

const verbose = cli.flags.verbose
const quiet = cli.flags.quiet

if (verbose) {
  console.log(cli.flags)
}

/* eslint-disable dot-notation */
const outputFileMatrix = {
  "node-classic-commonjs": PKG["main"] || null,
  "node-classic-esmodule": PKG["module"] || PKG["jsnext:main"] || null,
  "node-modern-commonjs": PKG["main:modern"] || null,
  "node-modern-esmodule": PKG["module:modern"] || null,
  "browser-classic-esmodule": PKG["browser"] || PKG["web"] || PKG["browserify"] || null,
  "browser-modern-esmodule": PKG["browser:modern"] || PKG["web:modern"] || PKG["browserify:modern"] || null
}

const outputFolder = cli.flags.outputFolder
if (outputFolder) {
  outputFileMatrix["node-classic-commonjs"] = `${outputFolder}/node.classic.commonjs.js`
  outputFileMatrix["node-classic-esmodule"] = `${outputFolder}/node.classic.esmodule.js`
  outputFileMatrix["node-modern-commonjs"] = `${outputFolder}/node.modern.commonjs.js`
  outputFileMatrix["node-modern-esmodule"] = `${outputFolder}/node.modern.esmodule.js`
  outputFileMatrix["browser-classic-esmodule"] = `${outputFolder}/browser.classic.esmodule.js`
  outputFileMatrix["browser-modern-esmodule"] = `${outputFolder}/browser.modern.esmodule.js`
}

// Rollups support these formats: 'amd', 'cjs', 'es', 'iife', 'umd'
const format2Rollup = {
  commonjs: "cjs",
  esmodule: "es"
}

const moduleId = PKG.name
const moduleName = camelCase(moduleId)
const banner = getBanner(PKG)
const envs = {}
const formats = [ "esmodule", "commonjs" ]
const transpilers = getTranspilers("react", {
  minified: cli.flags.minified
})

if (cli.flags.entryNode) {
  envs.node = [ cli.flags.entryNode ]
} else {
  envs.node = [ "src/index.js", "module/index.js", "src/server/index.js" ]
}

if (cli.flags.entryBrowser) {
  envs.browser = [ cli.flags.entryBrowser ]
} else {
  envs.browser = [ "src/browser/index.js", "src/client/index.js", "src/browser.js", "src/client.js", "src/web.js" ]
}

eachOfSeries(envs, (envEntries, envId, envCallback) =>
{
  var entry = lookupBest(envEntries)
  if (entry)
  {
    if (!quiet) {
      console.log(`Using entry ${entry} for environment ${envId}`)
    }

    eachOfSeries(formats, (format, formatIndex, formatCallback) =>
    {
      eachOfSeries(transpilers, (currentTranspiler, transpilerId, variantCallback) =>
      {
        var destFile = outputFileMatrix[`${envId}-${transpilerId}-${format}`]
        if (destFile) {
          return bundleTo({ entry, envId, transpilerId, currentTranspiler, format, destFile, variantCallback })
        } else {
          return variantCallback(null)
        }
      }, formatCallback)
    }, envCallback)
  }
  else
  {
    envCallback(null)
  }
})

function lookupBest(candidates) {
  var filtered = candidates.filter(fileExists)
  return filtered[0]
}

function bundleTo({ entry, envId, transpilerId, currentTranspiler, format, destFile, variantCallback }) {
  if (!quiet) {
    console.log(`Bundling ${PKG.name} v${PKG.version} as ${transpilerId} defined as ${format} to ${destFile}...`)
  }

  var variables = {
    "process.env.NAME": JSON.stringify(PKG.name),
    "process.env.VERSION": JSON.stringify(PKG.version),
    "process.env.TARGET": JSON.stringify(envId)
  }

  var fileRelink = relink({ outputFolder, entry, verbose })
  rollup({
    entry,
    cache,
    onwarn: (msg) => console.warn(msg),
    external(dependency)
    {
      if (dependency === entry) {
        return false
      }

      if (fileRelink.isExternal(dependency)) {
        return true
      }

      if (isAbsolute(dependency)) {
        var rel = relative(CWD, dependency)
        return Boolean(/node_modules/.exec(rel))
      }

      return dependency.charAt(0) !== "."
    },
    plugins:
    [
      nodeResolve({
        extensions: [ ".js", ".jsx", ".ts", ".tsx", ".json" ],
        jsnext: true,
        module: true,
        main: true
      }),
      jsonPlugin,
      yamlPlugin,
      replacePlugin(variables),
      currentTranspiler,
      fileRelink
    ]
  })
    .then((bundle) =>
      bundle.write({
        format: format2Rollup[format],
        moduleId,
        moduleName,
        banner,
        sourceMap: cli.flags.sourcemap,
        dest: destFile
      })
    )
    .then(() =>
      variantCallback(null)
    )
    .catch((err) =>
    {
      console.error(err)
      variantCallback(`Error during bundling ${format}: ${err}`)
    })
}
<commit_msg>Fixed self-replacement issues during publish<commit_after>import { resolve, relative, isAbsolute } from "path"
import { eachOfSeries } from "async"
import { camelCase } from "lodash"
import fileExists from "file-exists"
import meow from "meow"

import { rollup } from "rollup"
import relink from "rollup-plugin-relink"
import nodeResolve from "rollup-plugin-node-resolve"
import jsonPlugin from "rollup-plugin-json"
import yamlPlugin from "rollup-plugin-yaml"
import replacePlugin from "rollup-plugin-replace"

import getTranspilers from "./getTranspilers"
import getBanner from "./getBanner"

const CWD = process.cwd()
const PKG = require(resolve(CWD, "package.json"))

var cache

const cli = meow(`
  Usage
    $ prepublish-lib

  Options
    --entry-node      Entry file for NodeJS environment [default = auto]
    --entry-browser   Entry file for Browser environment [default = auto]

    --output-folder   Configure the output folder [default = auto]

    -t, --transpiler  Chose the transpiler/config to use. Either "react", "latest" or "buble". [default = latest]
    -x, --minified    Enabled minification of output files
    -m, --sourcemap   Create a source map file during processing

    -v, --verbose     Verbose output mode [default = false]
    -q, --quiet       Quiet output mode [default = false]
`, {
  default: {
    entryNode: null,
    entryBrowser: null,

    outputFolder: null,

    transpiler: "react",
    minified: false,
    sourcemap: true,

    verbose: false,
    quiet: false
  }
})

const verbose = cli.flags.verbose
const quiet = cli.flags.quiet

if (verbose) {
  console.log(cli.flags)
}

/* eslint-disable dot-notation */
const outputFileMatrix = {
  "node-classic-commonjs": PKG["main"] || null,
  "node-classic-esmodule": PKG["module"] || PKG["jsnext:main"] || null,
  "node-modern-commonjs": PKG["main:modern"] || null,
  "node-modern-esmodule": PKG["module:modern"] || null,
  "browser-classic-esmodule": PKG["browser"] || PKG["web"] || PKG["browserify"] || null,
  "browser-modern-esmodule": PKG["browser:modern"] || PKG["web:modern"] || PKG["browserify:modern"] || null
}

const outputFolder = cli.flags.outputFolder
if (outputFolder) {
  outputFileMatrix["node-classic-commonjs"] = `${outputFolder}/node.classic.commonjs.js`
  outputFileMatrix["node-classic-esmodule"] = `${outputFolder}/node.classic.esmodule.js`
  outputFileMatrix["node-modern-commonjs"] = `${outputFolder}/node.modern.commonjs.js`
  outputFileMatrix["node-modern-esmodule"] = `${outputFolder}/node.modern.esmodule.js`
  outputFileMatrix["browser-classic-esmodule"] = `${outputFolder}/browser.classic.esmodule.js`
  outputFileMatrix["browser-modern-esmodule"] = `${outputFolder}/browser.modern.esmodule.js`
}

// Rollups support these formats: 'amd', 'cjs', 'es', 'iife', 'umd'
const format2Rollup = {
  commonjs: "cjs",
  esmodule: "es"
}

const moduleId = PKG.name
const moduleName = camelCase(moduleId)
const banner = getBanner(PKG)
const envs = {}
const formats = [ "esmodule", "commonjs" ]
const transpilers = getTranspilers("react", {
  minified: cli.flags.minified
})

if (cli.flags.entryNode) {
  envs.node = [ cli.flags.entryNode ]
} else {
  envs.node = [ "src/index.js", "module/index.js", "src/server/index.js" ]
}

if (cli.flags.entryBrowser) {
  envs.browser = [ cli.flags.entryBrowser ]
} else {
  envs.browser = [ "src/browser/index.js", "src/client/index.js", "src/browser.js", "src/client.js", "src/web.js" ]
}

eachOfSeries(envs, (envEntries, envId, envCallback) =>
{
  var entry = lookupBest(envEntries)
  if (entry)
  {
    if (!quiet) {
      console.log(`Using entry ${entry} for environment ${envId}`)
    }

    eachOfSeries(formats, (format, formatIndex, formatCallback) =>
    {
      eachOfSeries(transpilers, (currentTranspiler, transpilerId, variantCallback) =>
      {
        var destFile = outputFileMatrix[`${envId}-${transpilerId}-${format}`]
        if (destFile) {
          return bundleTo({ entry, envId, transpilerId, currentTranspiler, format, destFile, variantCallback })
        } else {
          return variantCallback(null)
        }
      }, formatCallback)
    }, envCallback)
  }
  else
  {
    envCallback(null)
  }
})

function lookupBest(candidates) {
  var filtered = candidates.filter(fileExists)
  return filtered[0]
}

function bundleTo({ entry, envId, transpilerId, currentTranspiler, format, destFile, variantCallback }) {
  if (!quiet) {
    console.log(`Bundling ${PKG.name} v${PKG.version} as ${transpilerId} defined as ${format} to ${destFile}...`)
  }

  var prefix = "process.env."
  var variables = {
    [`${prefix}NAME`]: JSON.stringify(PKG.name),
    [`${prefix}VERSION`]: JSON.stringify(PKG.version),
    [`${prefix}TARGET`]: JSON.stringify(envId)
  }

  var fileRelink = relink({ outputFolder, entry, verbose })
  rollup({
    entry,
    cache,
    onwarn: (msg) => console.warn(msg),
    external(dependency)
    {
      if (dependency === entry) {
        return false
      }

      if (fileRelink.isExternal(dependency)) {
        return true
      }

      if (isAbsolute(dependency)) {
        var rel = relative(CWD, dependency)
        return Boolean(/node_modules/.exec(rel))
      }

      return dependency.charAt(0) !== "."
    },
    plugins:
    [
      nodeResolve({
        extensions: [ ".js", ".jsx", ".ts", ".tsx", ".json" ],
        jsnext: true,
        module: true,
        main: true
      }),
      jsonPlugin,
      yamlPlugin,
      replacePlugin(variables),
      currentTranspiler,
      fileRelink
    ]
  })
    .then((bundle) =>
      bundle.write({
        format: format2Rollup[format],
        moduleId,
        moduleName,
        banner,
        sourceMap: cli.flags.sourcemap,
        dest: destFile
      })
    )
    .then(() =>
      variantCallback(null)
    )
    .catch((err) =>
    {
      console.error(err)
      variantCallback(`Error during bundling ${format}: ${err}`)
    })
}
<|endoftext|>