<commit_before>'use strict';

var escape = require('./lodash/escape');

var Selectivity = require('./selectivity-base');

require('./selectivity-locale');

/**
 * Default set of templates to use with Selectivity.js.
 *
 * Note that every template can be defined as either a string, a function returning a string (like
 * Handlebars templates, for instance) or as an object containing a render function (like Hogan.js
 * templates, for instance).
 */
Selectivity.Templates = {

    /**
     * Renders the dropdown.
     *
     * The template is expected to have at least one element with the class
     * 'selectivity-results-container', which is where all results will be added to.
     *
     * @param options Options object containing the following properties:
     *                dropdownCssClass - Optional CSS class to add to the top-level element.
     *                searchInputPlaceholder - Optional placeholder text to display in the search
     *                                         input in the dropdown.
     *                showSearchInput - Boolean whether a search input should be shown. If true,
     *                                  an input element with the 'selectivity-search-input' is
     *                                  expected.
     */
    dropdown: function(options) {
        var extraClass = (options.dropdownCssClass ? ' ' + options.dropdownCssClass : ''),
            searchInput = '';
        if (options.showSearchInput) {
            extraClass += ' has-search-input';

            var placeholder = options.searchInputPlaceholder;
            searchInput = (
                '
' +
                    '<input type="text" class="selectivity-search-input"' +
                            (placeholder ? ' placeholder="' + escape(placeholder) + '"'
                                         : '') + '>' +
                '
'
            );
        }
        return (
            '
' +
                searchInput +
                '

' +
            '
'
        );
    },

    /**
     * Renders an error message in the dropdown.
     *
     * @param options Options object containing the following properties:
     *                escape - Boolean whether the message should be HTML-escaped.
     *                message - The message to display.
     */
    error: function(options) {
        return (
            '
' +
                (options.escape ? escape(options.message) : options.message) +
            '
'
        );
    },

    /**
     * Renders a loading indicator in the dropdown.
     *
     * This template is expected to have an element with a 'selectivity-loading' class which may be
     * replaced with actual results.
     */
    loading: function() {
        return '
' + Selectivity.Locale.loading + '
';
    },

    /**
     * Load more indicator.
     *
     * This template is expected to have an element with a 'selectivity-load-more' class which, when
     * clicked, will load more results.
     */
    loadMore: function() {
        return '
' + Selectivity.Locale.loadMore + '
';
    },

    /**
     * Renders multi-selection input boxes.
     *
     * The template is expected to have at least have elements with the following classes:
     * 'selectivity-multiple-input-container' - The element containing all the selected items and
     *                                          the input for selecting additional items.
     * 'selectivity-multiple-input' - The actual input element that allows the user to type to
     *                                search for more items. When selected items are added, they are
     *                                inserted right before this element.
     * 'selectivity-width-detector' - This element is optional, but important to make sure the
     *                                '.selectivity-multiple-input' element will fit in the
     *                                container. The width detector also has the
     *                                'select2-multiple-input' class on purpose to be able to detect
     *                                the width of text entered in the input element.
     *
     * @param options Options object containing the following property:
     *                enabled - Boolean whether the input is enabled.
     */
    multipleSelectInput: function(options) {
        return (
            '
' +
                (options.enabled ? '<input type="text" autocomplete="off" autocorrect="off" ' +
                                          'autocapitalize="off" ' +
                                          'class="selectivity-multiple-input">' +
                                   ''
                                 : '

') +
                '

' +
            '
'
        );
    },

    /**
     * Renders a selected item in multi-selection input boxes.
     *
     * The template is expected to have a top-level element with the class
     * 'selectivity-multiple-selected-item'. This element is also required to have a 'data-item-id'
     * attribute with the ID set to that passed through the options object.
     *
     * An element with the class 'selectivity-multiple-selected-item-remove' should be present
     * which, when clicked, will cause the element to be removed.
     *
     * @param options Options object containing the following properties:
     *                highlighted - Boolean whether this item is currently highlighted.
     *                id - Identifier for the item.
     *                removable - Boolean whether a remove icon should be displayed.
     *                text - Text label which the user sees.
     */
    multipleSelectedItem: function(options) {
        var extraClass = (options.highlighted ? ' highlighted' : '');
        return (
            '' +
                escape(options.text) +
                (options.removable ? '' +
                                         '' +
                                     ''
                                   : '') +
            ''
        );
    },

    /**
     * Renders a message there are no results for the given query.
     *
     * @param options Options object containing the following property:
     *                term - Search term the user is searching for.
     */
    noResults: function(options) {
        var Locale = Selectivity.Locale;
        return (
            '
' +
                (options.term ? Locale.noResultsForTerm(options.term) : Locale.noResults) +
            '
'
        );
    },

    /**
     * Renders a container for item children.
     *
     * The template is expected to have an element with the class 'selectivity-result-children'.
     *
     * @param options Options object containing the following property:
     *                childrenHtml - Rendered HTML for the children.
     */
    resultChildren: function(options) {
        return '
' + options.childrenHtml + '
';
    },

    /**
     * Render a result item in the dropdown.
     *
     * The template is expected to have a top-level element with the class
     * 'selectivity-result-item'. This element is also required to have a 'data-item-id' attribute
     * with the ID set to that passed through the options object.
     *
     * @param options Options object containing the following properties:
     *                id - Identifier for the item.
     *                text - Text label which the user sees.
     *                submenu - Truthy if the result item has a menu with subresults.
     */
    resultItem: function(options) {
        return (
            '
' +
                escape(options.text) +
                (options.submenu ? ''
                                 : '') +
            '
'
        );
    },

    /**
     * Render a result label in the dropdown.
     *
     * The template is expected to have a top-level element with the class
     * 'selectivity-result-label'.
     *
     * @param options Options object containing the following properties:
     *                text - Text label.
     */
    resultLabel: function(options) {
        return '
' + escape(options.text) + '
';
    },

    /**
     * Renders single-select input boxes.
     *
     * The template is expected to have at least one element with the class
     * 'selectivity-single-result-container' which is the element containing the selected item or
     * the placeholder.
     */
    singleSelectInput: (
        '
' +
            '<input type="text" class="selectivity-single-select-input">' +
            '

' +
            '' +
        '
'
    ),

    /**
     * Renders the placeholder for single-select input boxes.
     *
     * The template is expected to have a top-level element with the class
     * 'selectivity-placeholder'.
     *
     * @param options Options object containing the following property:
     *                placeholder - The placeholder text.
     */
    singleSelectPlaceholder: function(options) {
        return (
            '
' +
                escape(options.placeholder) +
            '
'
        );
    },

    /**
     * Renders the selected item in single-select input boxes.
     *
     * The template is expected to have a top-level element with the class
     * 'selectivity-single-selected-item'. This element is also required to have a 'data-item-id'
     * attribute with the ID set to that passed through the options object.
     *
     * @param options Options object containing the following properties:
     *                id - Identifier for the item.
     *                removable - Boolean whether a remove icon should be displayed.
     *                text - Text label which the user sees.
     */
    singleSelectedItem: function(options) {
        return (
            '' +
                (options.removable ? '' +
                                         '' +
                                     ''
                                   : '') +
                escape(options.text) +
            ''
        );
    },

    /**
     * Renders select-box inside single-select input that was initialized on
     * traditional <select> element.
     *
     * @param options Options object containing the following properties:
     *                name - Name of the <select> element.
     *                mode - Mode in which select exists, single or multiple.
     */
    selectCompliance: function(options) {
        return ('<select name="' + options.name + '"' + (options.mode === 'multiple' ? ' multiple' : '') + '></select>');
    },

    /**
     * Renders the selected item in compliance <select> element as <option>.
     *
     * @param options Options object containing the following properties
     *                id - Identifier for the item.
     *                text - Text label which the user sees.
     */
    selectOptionCompliance: function(options) {
        return (
            '<option value="' + escape(options.id) + '" selected>' +
                escape(options.text) +
            '</option>'
        );
    }

};
<commit_msg>Added fix for <select multiple> name that misses []<commit_after>'use strict';

var escape = require('./lodash/escape');

var Selectivity = require('./selectivity-base');

require('./selectivity-locale');

/**
 * Default set of templates to use with Selectivity.js.
 *
 * Note that every template can be defined as either a string, a function returning a string (like
 * Handlebars templates, for instance) or as an object containing a render function (like Hogan.js
 * templates, for instance).
 */
Selectivity.Templates = {

    /**
     * Renders the dropdown.
     *
     * The template is expected to have at least one element with the class
     * 'selectivity-results-container', which is where all results will be added to.
     *
     * @param options Options object containing the following properties:
     *                dropdownCssClass - Optional CSS class to add to the top-level element.
     *                searchInputPlaceholder - Optional placeholder text to display in the search
     *                                         input in the dropdown.
     *                showSearchInput - Boolean whether a search input should be shown. If true,
     *                                  an input element with the 'selectivity-search-input' is
     *                                  expected.
     */
    dropdown: function(options) {
        var extraClass = (options.dropdownCssClass ? ' ' + options.dropdownCssClass : ''),
            searchInput = '';
        if (options.showSearchInput) {
            extraClass += ' has-search-input';

            var placeholder = options.searchInputPlaceholder;
            searchInput = (
                '
' +
                    '<input type="text" class="selectivity-search-input"' +
                            (placeholder ? ' placeholder="' + escape(placeholder) + '"'
                                         : '') + '>' +
                '
'
            );
        }
        return (
            '
' +
                searchInput +
                '

' +
            '
'
        );
    },

    /**
     * Renders an error message in the dropdown.
     *
     * @param options Options object containing the following properties:
     *                escape - Boolean whether the message should be HTML-escaped.
     *                message - The message to display.
     */
    error: function(options) {
        return (
            '
' +
                (options.escape ? escape(options.message) : options.message) +
            '
'
        );
    },

    /**
     * Renders a loading indicator in the dropdown.
     *
     * This template is expected to have an element with a 'selectivity-loading' class which may be
     * replaced with actual results.
     */
    loading: function() {
        return '
' + Selectivity.Locale.loading + '
';
    },

    /**
     * Load more indicator.
     *
     * This template is expected to have an element with a 'selectivity-load-more' class which, when
     * clicked, will load more results.
     */
    loadMore: function() {
        return '
' + Selectivity.Locale.loadMore + '
';
    },

    /**
     * Renders multi-selection input boxes.
     *
     * The template is expected to have at least have elements with the following classes:
     * 'selectivity-multiple-input-container' - The element containing all the selected items and
     *                                          the input for selecting additional items.
     * 'selectivity-multiple-input' - The actual input element that allows the user to type to
     *                                search for more items. When selected items are added, they are
     *                                inserted right before this element.
     * 'selectivity-width-detector' - This element is optional, but important to make sure the
     *                                '.selectivity-multiple-input' element will fit in the
     *                                container. The width detector also has the
     *                                'select2-multiple-input' class on purpose to be able to detect
     *                                the width of text entered in the input element.
     *
     * @param options Options object containing the following property:
     *                enabled - Boolean whether the input is enabled.
     */
    multipleSelectInput: function(options) {
        return (
            '
' +
                (options.enabled ? '<input type="text" autocomplete="off" autocorrect="off" ' +
                                          'autocapitalize="off" ' +
                                          'class="selectivity-multiple-input">' +
                                   ''
                                 : '

') +
                '

' +
            '
'
        );
    },

    /**
     * Renders a selected item in multi-selection input boxes.
     *
     * The template is expected to have a top-level element with the class
     * 'selectivity-multiple-selected-item'. This element is also required to have a 'data-item-id'
     * attribute with the ID set to that passed through the options object.
     *
     * An element with the class 'selectivity-multiple-selected-item-remove' should be present
     * which, when clicked, will cause the element to be removed.
     *
     * @param options Options object containing the following properties:
     *                highlighted - Boolean whether this item is currently highlighted.
     *                id - Identifier for the item.
     *                removable - Boolean whether a remove icon should be displayed.
     *                text - Text label which the user sees.
     */
    multipleSelectedItem: function(options) {
        var extraClass = (options.highlighted ? ' highlighted' : '');
        return (
            '' +
                escape(options.text) +
                (options.removable ? '' +
                                         '' +
                                     ''
                                   : '') +
            ''
        );
    },

    /**
     * Renders a message there are no results for the given query.
     *
     * @param options Options object containing the following property:
     *                term - Search term the user is searching for.
     */
    noResults: function(options) {
        var Locale = Selectivity.Locale;
        return (
            '
' +
                (options.term ? Locale.noResultsForTerm(options.term) : Locale.noResults) +
            '
'
        );
    },

    /**
     * Renders a container for item children.
     *
     * The template is expected to have an element with the class 'selectivity-result-children'.
     *
     * @param options Options object containing the following property:
     *                childrenHtml - Rendered HTML for the children.
     */
    resultChildren: function(options) {
        return '
' + options.childrenHtml + '
';
    },

    /**
     * Render a result item in the dropdown.
     *
     * The template is expected to have a top-level element with the class
     * 'selectivity-result-item'. This element is also required to have a 'data-item-id' attribute
     * with the ID set to that passed through the options object.
     *
     * @param options Options object containing the following properties:
     *                id - Identifier for the item.
     *                text - Text label which the user sees.
     *                submenu - Truthy if the result item has a menu with subresults.
     */
    resultItem: function(options) {
        return (
            '
' +
                escape(options.text) +
                (options.submenu ? ''
                                 : '') +
            '
'
        );
    },

    /**
     * Render a result label in the dropdown.
     *
     * The template is expected to have a top-level element with the class
     * 'selectivity-result-label'.
     *
     * @param options Options object containing the following properties:
     *                text - Text label.
     */
    resultLabel: function(options) {
        return '
' + escape(options.text) + '
';
    },

    /**
     * Renders single-select input boxes.
     *
     * The template is expected to have at least one element with the class
     * 'selectivity-single-result-container' which is the element containing the selected item or
     * the placeholder.
     */
    singleSelectInput: (
        '
' +
            '<input type="text" class="selectivity-single-select-input">' +
            '

' +
            '' +
        '
'
    ),

    /**
     * Renders the placeholder for single-select input boxes.
     *
     * The template is expected to have a top-level element with the class
     * 'selectivity-placeholder'.
     *
     * @param options Options object containing the following property:
     *                placeholder - The placeholder text.
     */
    singleSelectPlaceholder: function(options) {
        return (
            '
' +
                escape(options.placeholder) +
            '
'
        );
    },

    /**
     * Renders the selected item in single-select input boxes.
     *
     * The template is expected to have a top-level element with the class
     * 'selectivity-single-selected-item'. This element is also required to have a 'data-item-id'
     * attribute with the ID set to that passed through the options object.
     *
     * @param options Options object containing the following properties:
     *                id - Identifier for the item.
     *                removable - Boolean whether a remove icon should be displayed.
     *                text - Text label which the user sees.
     */
    singleSelectedItem: function(options) {
        return (
            '' +
                (options.removable ? '' +
                                         '' +
                                     ''
                                   : '') +
                escape(options.text) +
            ''
        );
    },

    /**
     * Renders select-box inside single-select input that was initialized on
     * traditional <select> element.
     *
     * @param options Options object containing the following properties:
     *                name - Name of the <select> element.
     *                mode - Mode in which select exists, single or multiple.
     */
    selectCompliance: function(options) {
        if (!options.name.match(/\[\]$/)) {
            options.name = options.name + '[]';
        }
        return ('<select name="' + options.name + '"' + (options.mode === 'multiple' ? ' multiple' : '') + '></select>');
    },

    /**
     * Renders the selected item in compliance <select> element as <option>.
     *
     * @param options Options object containing the following properties
     *                id - Identifier for the item.
     *                text - Text label which the user sees.
     */
    selectOptionCompliance: function(options) {
        return (
            '<option value="' + escape(options.id) + '" selected>' +
                escape(options.text) +
            '</option>'
        );
    }

};
<|endoftext|>


<commit_before>/**
 * A simple JSON search
 * Requires jQuery (v 1.7+)
 *
 * @author  Mat Hayward - Erskine Design - https://github.com/mathaywarduk/jekyll-search
 * @version  0.1
 */

 /* ==========================================================================
    Initialisation
    ========================================================================== */

var q, jsonFeedUrl = "/feeds/feed.json",
    $searchForm = $("[data-search-form]"),
    $searchInput = $("[data-search-input]"),
    $resultTemplate = $("#search-result"),
    $resultsPlaceholder = $("[data-search-results]"),
    $foundContainer = $("[data-search-found]"),
    $foundTerm = $("[data-search-found-term]"),
    $foundCount = $("[data-search-found-count]"),
    allowEmpty = true,
    showLoader = true,
    loadingClass = "is--loading";

$(document).ready( function() {

    // hide items found string
    $foundContainer.hide();

    // initiate search functionality
    initSearch();
});

 /* ==========================================================================
    Search functions
    ========================================================================== */

/**
 * Initiate search functionality.
 * Shows results based on querystring if present.
 * Binds search function to form submission.
 */
function initSearch() {

    // Get search results if q parameter is set in querystring
    if (getParameterByName('q')) {
        q = decodeURIComponent(getParameterByName('q'));
        $searchInput.val(q);
        execSearch(q);
    }

    // Get search results on submission of form
    $(document).on("submit", $searchForm, function(e) {
        e.preventDefault();
        q = $searchInput.val();
        execSearch(q);
    });
}

/**
 * Executes search
 * @param {String} q
 * @return null
 */
function execSearch(q) {
    if (q != '' || allowEmpty) {
        if (showLoader) {
            toggleLoadingClass();
        }

        getSearchResults(processData());
    }
}

/**
 * Toggles loading class on results and found string
 * @return null
 */
function toggleLoadingClass() {
    $resultsPlaceholder.toggleClass(loadingClass);
    $foundContainer.toggleClass(loadingClass);
}

/**
 * Get Search results from JSON
 * @param {Function} callbackFunction
 * @return null
 */
function getSearchResults(callbackFunction) {
    $.get(jsonFeedUrl, callbackFunction, 'json');
}

/**
 * Process search result data
 * @return null
 */
function processData() {
    $results = [];

    return function(data) {

        var resultsCount = 0,
            results = "";

        $.each(data, function(index, item) {
            // check if search term is in content or title
            if (item.content.toLowerCase().indexOf(q.toLowerCase()) > -1 || item.title.toLowerCase().indexOf(q.toLowerCase()) > -1) {
                var result = populateResultContent($resultTemplate.html(), item);
                resultsCount++;
                results += result;
            }
        });

        if (showLoader) {
            toggleLoadingClass();
        }

        populateResultsString(resultsCount);
        showSearchResults(results);
    }
}

/**
 * Add search results to placeholder
 * @param {String} results
 * @return null
 */
function showSearchResults(results) {
    // Add results HTML to placeholder
    $resultsPlaceholder.html(results);
}

/**
 * Add results content to item template
 * @param {String} html
 * @param {object} item
 * @return {String} Populated HTML
 */
function populateResultContent(html, item) {
    html = injectContent(html, item.title, '##Title##');
    html = injectContent(html, item.link, '##Url##');
    html = injectContent(html, item.excerpt, '##Excerpt##');
    html = injectContent(html, item.date, '##Date##');
    return html;
}

/**
 * Populates results string
 * @param {String} count
 * @return null
 */
function populateResultsString(count) {
    $foundTerm.text(q);
    $foundCount.text(count);
    $foundContainer.show();
}

 /* ==========================================================================
    Helper functions
    ========================================================================== */

/**
 * Gets query string parameter - taken from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
 * @param {String} name
 * @return {String} parameter value
 */
function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

/**
 * Injects content into template using placeholder
 * @param {String} originalContent
 * @param {String} injection
 * @param {String} placeholder
 * @return {String} injected content
 */
function injectContent(originalContent, injection, placeholder) {
    var regex = new RegExp(placeholder, 'g');
    return originalContent.replace(regex, injection);
}<commit_msg>Added new post<commit_after>/**
 * A simple JSON search
 * Requires jQuery (v 1.7+)
 *
 * @author  Mat Hayward - Erskine Design
 * @version  0.1
 */

 /* ==========================================================================
    Initialisation
    ========================================================================== */

var q, jsonFeedUrl = "/feeds/feed.json",
    $searchForm = $("[data-search-form]"),
    $searchInput = $("[data-search-input]"),
    $resultTemplate = $("#search-result"),
    $resultsPlaceholder = $("[data-search-results]"),
    $foundContainer = $("[data-search-found]"),
    $foundTerm = $("[data-search-found-term]"),
    $foundCount = $("[data-search-found-count]"),
    allowEmpty = true,
    showLoader = true,
    loadingClass = "is--loading";

$(document).ready( function() {
    // hide items found string
    $foundContainer.hide();

    // initiate search functionality
    initSearch();
});

 /* ==========================================================================
    Search functions
    ========================================================================== */

/**
 * Initiate search functionality.
 * Shows results based on querystring if present.
 * Binds search function to form submission.
 */
function initSearch() {

    // Get search results if q parameter is set in querystring
    if (getParameterByName('q')) {
        q = decodeURIComponent(getParameterByName('q'));
        $searchInput.val(q);
        execSearch(q);
    }

    // Get search results on submission of form
    $(document).on("submit", $searchForm, function(e) {
        e.preventDefault();
        q = $searchInput.val();
        execSearch(q);
    });
}

/**
 * Executes search
 * @param {String} q
 * @return null
 */
function execSearch(q) {
    if (q != '' || allowEmpty) {
        if (showLoader) {
            toggleLoadingClass();
        }

        getSearchResults(processData());
    }
}

/**
 * Toggles loading class on results and found string
 * @return null
 */
function toggleLoadingClass() {
    $resultsPlaceholder.toggleClass(loadingClass);
    $foundContainer.toggleClass(loadingClass);
}

/**
 * Get Search results from JSON
 * @param {Function} callbackFunction
 * @return null
 */
function getSearchResults(callbackFunction) {
    $.get(jsonFeedUrl, callbackFunction, 'json');
}

/**
 * Process search result data
 * @return null
 */
function processData() {
    $results = [];

    return function(data) {

        var resultsCount = 0,
            results = "";

        $.each(data, function(index, item) {
            // check if search term is in content or title
            if (item.search_omit != "true" && (item.content.toLowerCase().indexOf(q.toLowerCase()) > -1 || item.title.toLowerCase().indexOf(q.toLowerCase()) > -1)) {
                var result = populateResultContent($resultTemplate.html(), item);
                resultsCount++;
                results += result;
            }
        });

        if (showLoader) {
            toggleLoadingClass();
        }

        populateResultsString(resultsCount);
        showSearchResults(results);
    }
}

/**
 * Add search results to placeholder
 * @param {String} results
 * @return null
 */
function showSearchResults(results) {
    // Add results HTML to placeholder
    $resultsPlaceholder.html(results);
}

/**
 * Add results content to item template
 * @param {String} html
 * @param {object} item
 * @return {String} Populated HTML
 */
function populateResultContent(html, item) {
    html = injectContent(html, item.title, '##Title##');
    html = injectContent(html, item.link, '##Url##');
    html = injectContent(html, item.excerpt, '##Excerpt##');
    html = injectContent(html, item.date, '##Date##');
    return html;
}

/**
 * Populates results string
 * @param {String} count
 * @return null
 */
function populateResultsString(count) {
    $foundTerm.text(q);
    $foundCount.text(count);
    $foundContainer.show();
}

 /* ==========================================================================
    Helper functions
    ========================================================================== */

/**
 * Gets query string parameter - taken from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
 * @param {String} name
 * @return {String} parameter value
 */
function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

/**
 * Injects content into template using placeholder
 * @param {String} originalContent
 * @param {String} injection
 * @param {String} placeholder
 * @return {String} injected content
 */
function injectContent(originalContent, injection, placeholder) {
    var regex = new RegExp(placeholder, 'g');
    return originalContent.replace(regex, injection);
}
<|endoftext|>


<commit_before>// @flow

import nanomatch from 'nanomatch'
import { createFileTransformer } from 'pundle-api'

import manifest from '../package.json'
import { getBabelCore } from './helpers'

const DEFAULT_EXCLUDE = ['node_modules/**']
export default function({
  exclude = DEFAULT_EXCLUDE,
  processOutsideProjectRoot,
}: { exclude?: Array<string | RegExp>, processOutsideProjectRoot?: boolean } = {}) {
  return createFileTransformer({
    name: 'pundle-transformer-babel',
    version: manifest.version,
    priority: 1250,
    async callback({ file, context }) {
      if (file.format !== 'js') return null

      if (exclude.some(item => nanomatch.isMatch(file.filePath, item))) {
        // Excluded
        return null
      }
      if (!processOutsideProjectRoot && !file.filePath.startsWith(context.config.rootDirectory)) {
        // Outside project root
        return null
      }

      const babelCore = getBabelCore(context.config.rootDirectory)
      if (!babelCore) {
        throw new Error(`Babel not found in '${context.config.rootDirectory}' (tried @babel/core & babel-core)`)
      }

      const transformed = await new Promise((resolve, reject) => {
        babelCore.transform(
          file.contents,
          {
            root: context.config.rootDirectory,
            babelrc: true,
            filename: file.filePath,
            sourceMap: true,
            sourceType: 'module',
            highlightCode: false,
            sourceFileName: file.filePath,
          },
          function(err, result) {
            if (err) {
              reject(err)
            } else resolve(result)
          },
        )
      })

      return {
        contents: transformed.code,
        sourceMap: transformed.map,
      }
    },
  })
}
<commit_msg>:new: Expose raw babel options in transformer-babel<commit_after>// @flow

import nanomatch from 'nanomatch'
import { createFileTransformer } from 'pundle-api'

import manifest from '../package.json'
import { getBabelCore } from './helpers'

const DEFAULT_EXCLUDE = ['node_modules/**']
export default function({
  exclude = DEFAULT_EXCLUDE,
  processOutsideProjectRoot,
  options = {},
}: { exclude?: Array<string | RegExp>, processOutsideProjectRoot?: boolean, options: ?Object } = {}) {
  return createFileTransformer({
    name: 'pundle-transformer-babel',
    version: manifest.version,
    priority: 1250,
    async callback({ file, context }) {
      if (file.format !== 'js') return null

      if (exclude.some(item => nanomatch.isMatch(file.filePath, item))) {
        // Excluded
        return null
      }
      if (!processOutsideProjectRoot && !file.filePath.startsWith(context.config.rootDirectory)) {
        // Outside project root
        return null
      }

      const babelCore = getBabelCore(context.config.rootDirectory)
      if (!babelCore) {
        throw new Error(`Babel not found in '${context.config.rootDirectory}' (tried @babel/core & babel-core)`)
      }

      const transformed = await new Promise((resolve, reject) => {
        babelCore.transform(
          file.contents,
          {
            root: context.config.rootDirectory,
            babelrc: true,
            filename: file.filePath,
            sourceMap: true,
            sourceType: 'module',
            highlightCode: false,
            sourceFileName: file.filePath,
            ...options,
          },
          function(err, result) {
            if (err) {
              reject(err)
            } else resolve(result)
          },
        )
      })

      return {
        contents: transformed.code,
        sourceMap: transformed.map,
      }
    },
  })
}
<|endoftext|>


<commit_before>Flyous = (function() {
	var divId = 'Flyous',
			fps = 10,
			latency = null,
			sprite,

			animation = function() {
				sprite.frame += 1;
				if (sprite.frame >= sprite.frames) {
					sprite.frame = 0;
				}

				sprite.div.style.backgroundPosition = -(sprite.frame * sprite.width) + 'px' + ' 0';

				sprite.timer = setTimeout(animation, latency);
			},

			createDomElement = function() {
				sprite.div = document.createElement('div');
					sprite.div.id = divId;
					sprite.div.style.width = sprite.width + 'px';
					sprite.div.style.height = sprite.height + 'px';
					sprite.div.style.position = 'absolute';
					sprite.div.style.left = '100px';
					sprite.div.style.top = '100px';
					sprite.div.style.zIndex = '10000';
					sprite.div.style.backgroundImage = 'url(' + sprite.image + ')';

				document.body.appendChild(sprite.div);
			},

			move = function(e) {
				sprite.div.style.left = e.clientX + sprite.width+ 'px';
				sprite.div.style.top = e.clientY + sprite.height + 'px';
			},

			// Runs when sprite finishes loading.
			initSprite = function() {
				sprite.frames = this.width / this.height;
				createDomElement();
				document.documentElement.onmousemove = move;

				sprite.timer = setTimeout(animation, latency);
				window.anim = animation;
			};

			init = function(obj) {
				sprite = {
					image: obj.image || false,
					width: obj.width || 0,
					height: obj.height || 0,
					fps: obj.fps || fps,
					frames: 0,
					frame: 0,
					img: null
				};

				if (!sprite.image) {
					return false;
				}

				sprite.img = new Image();
					sprite.img.onload = initSprite;
					sprite.img.src = sprite.image;

				latency = 1000 / sprite.fps;

				return true;
			};

	// Returns public functions.
	// TODO how does this really work?!
	return {
		start: function(sprite) {
			return init(sprite);
		},
		// stop: function(id) {
		// 	return true;
		// }
	}
})();<commit_msg>* Removes unneccessary debug window.anim = ...;<commit_after>Flyous = (function() {
	var divId = 'Flyous',
			fps = 10,
			latency = null,
			sprite,

			animation = function() {
				sprite.frame += 1;
				if (sprite.frame >= sprite.frames) {
					sprite.frame = 0;
				}

				sprite.div.style.backgroundPosition = -(sprite.frame * sprite.width) + 'px' + ' 0';

				sprite.timer = setTimeout(animation, latency);
			},

			createDomElement = function() {
				sprite.div = document.createElement('div');
					sprite.div.id = divId;
					sprite.div.style.width = sprite.width + 'px';
					sprite.div.style.height = sprite.height + 'px';
					sprite.div.style.position = 'absolute';
					sprite.div.style.left = '100px';
					sprite.div.style.top = '100px';
					sprite.div.style.zIndex = '10000';
					sprite.div.style.backgroundImage = 'url(' + sprite.image + ')';

				document.body.appendChild(sprite.div);
			},

			move = function(e) {
				sprite.div.style.left = e.clientX + sprite.width+ 'px';
				sprite.div.style.top = e.clientY + sprite.height + 'px';
			},

			// Runs when sprite finishes loading.
			initSprite = function() {
				sprite.frames = this.width / this.height;
				createDomElement();
				document.documentElement.onmousemove = move;

				sprite.timer = setTimeout(animation, latency);
			};

			init = function(obj) {
				sprite = {
					image: obj.image || false,
					width: obj.width || 0,
					height: obj.height || 0,
					fps: obj.fps || fps,
					frames: 0,
					frame: 0,
					img: null
				};

				if (!sprite.image) {
					return false;
				}

				sprite.img = new Image();
					sprite.img.onload = initSprite;
					sprite.img.src = sprite.image;

				latency = 1000 / sprite.fps;

				return true;
			};

	// Returns public functions.
	// TODO how does this really work?!
	return {
		start: function(sprite) {
			return init(sprite);
		},
		// stop: function(id) {
		// 	return true;
		// }
	}
})();<|endoftext|>


<commit_before>/*
 * (C) 2013 Gavin Lloyd <gavinhungry@gmail.com>
 * Regularish: a JavaScript regular expression editor
 */

yepnope([
  {
    test: window.JSON,
    nope: '//cdnjs.cloudflare.com/ajax/libs/json3/3.2.4/json3.min.js'
  }, {
    test: window.atob && window.btoa,
    nope: '/js/base64.min.js' // github.com/davidchambers/Base64.js
  },
  '//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js',
  '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.0/underscore-min.js',
  '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js',
  '/js/slade.min.js'
]);
<commit_msg>update json3 3.2.4 => 3.2.5<commit_after>/*
 * (C) 2013 Gavin Lloyd <gavinhungry@gmail.com>
 * Regularish: a JavaScript regular expression editor
 */

yepnope([
  {
    test: window.JSON,
    nope: '//cdnjs.cloudflare.com/ajax/libs/json3/3.2.5/json3.min.js'
  }, {
    test: window.atob && window.btoa,
    nope: '/js/base64.min.js' // github.com/davidchambers/Base64.js
  },
  '//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js',
  '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.0/underscore-min.js',
  '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js',
  '/js/slade.min.js'
]);
<|endoftext|>


<commit_before>// will be changed during build-time by babel-preset-env from webpack config
import '@babel/polyfill';
// not included by the above, review here: https://github.com/zloirock/core-js#stage-4-proposals
// eslint-disable-next-line import/no-extraneous-dependencies
import 'core-js/stage/4';
// eslint-disable-next-line import/no-extraneous-dependencies
import 'core-js/stage/3';

export default {};
<commit_msg>replace @babel/polyfill with core-js/stable<commit_after>// will be changed during build-time by babel-preset-env from webpack config
import 'core-js/stable';
// not included by the above, review here: https://github.com/zloirock/core-js#stage-4-proposals
// eslint-disable-next-line import/no-extraneous-dependencies
import 'core-js/stage/4';
// eslint-disable-next-line import/no-extraneous-dependencies
import 'core-js/stage/3';

export default {};
<|endoftext|>


<commit_before>var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    models = require('../models');

module.exports = function (app) {
    passport.use(new LocalStrategy(
        function (username, password, done) {
          models.User.find({ where: {username: username} })
            .then(function (user) {
              if (!user || !user.validate_password(password)) {
                return done(null, false, {message: 'Incorrect username or password'});
              }
              done(null, user);
            })
            .catch(function (err) {
              done(err);
            });
        }
    ));

    passport.serializeUser(function (user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function (id, done) {
      models.User.find(id)
        .then(function (user) {
          done(null, user);
        })
        .catch(function (err) {
          done(err);
        });
    });

    app.use(passport.initialize());
    app.use(passport.session());
};
<commit_msg>fix sequelize migration issue<commit_after>var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    models = require('../models');

module.exports = function (app) {
    passport.use(new LocalStrategy(
        function (username, password, done) {
          models.User.find({ where: {username: username} })
            .then(function (user) {
              if (!user || !user.validate_password(password)) {
                return done(null, false, {message: 'Incorrect username or password'});
              }
              done(null, user);
            })
            .catch(function (err) {
              done(err);
            });
        }
    ));

    passport.serializeUser(function (user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function (id, done) {
      models.User.findById(id)
        .then(function (user) {
          done(null, user);
        })
        .catch(function (err) {
          done(err);
        });
    });

    app.use(passport.initialize());
    app.use(passport.session());
};
<|endoftext|>


<commit_before>import { Component, PropTypes } from 'react';
import { connect }              from 'react-redux';

import classNames               from 'classnames';

import Icon                     from '../application/icon.component';
import UserAvatar               from '../application/user_avatar.component';
import FlagActions              from '../application/flag_actions.component';
import DangerLink               from '../application/danger_link.component';

import ChildrenComments         from './children_comments.component';
import NewCommentForm           from './new_comment_form.component';

import * as actions             from './comments.actions';

import htmlToReact              from '../application/html_to_react';

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

    this.state = {
      showReplyForm: false
    };
  }

  render() {
    const { comment } = this.props;
    const { ancestry } = comment;

    if (ancestry) {
      return this.renderComment();
    } else {
      return (

          {this.renderComment()}

      );
    }
  }

  renderComment() {
    const {
      comment,
      commentable,
      flagComment,
      unFlagComment
    } = this.props;

    const { author, ancestry } = comment;

    const authorUrl = author ? `/users/${author.id}` : '#';

    return (
      <article id={`comment_${comment.id}`} className={`comment ${ancestry ? 'comment--nested' : ''}`}>

                  <UserAvatar user={author} />

                  {this.renderAuthorName()}

                <time dateTime={comment.created_at}>{' ' + comment.created_at}</time>

                  <FlagActions
                    flaggeable={comment}
                    flagAction={flagComment}
                    unFlagAction={unFlagComment}
                  />

            {this.renderAlignmentBadge()}
            {htmlToReact(comment.body)}

          <div id={`comment_${comment.id}_reply`} className="reply">
            {this.renderReplyAction()}
            {this.renderHideButton()}
            {this.renderHideAuthorButton()}
            <NewCommentForm
              commentable={commentable}
              visible={this.state.showReplyForm}
              onCommentCreated={() => this.setState({ showReplyForm: false })  }  parent={comment} />

          {this.renderVoteActionLinks()}

        <ChildrenComments comment={comment} commentable={commentable} />

    );
  }

  renderAuthorName() {
    const { author, as, administrator_id, moderator_id } = this.props.comment;

    if (author.hidden || author.erased) {
      return (
        {I18n.t("comments.comment.user_deleted")}
      );
    } else {
      if (as === 'administrator') {
        return (
          {`${I18n.t("comments.comment.admin")} #`}{administrator_id}
        );
      } else if (as === 'moderator') {
        return (
          {`${I18n.t("comments.comment.moderator")} #`}{moderator_id}
        );
      } else {
        return (
          <a href={`/users/${author.id}`}>{author.name}
        );
      }
    }
  }

  renderReplyAction() {
    const { commentable } = this.props;
    if (commentable.permissions.comment) {
      return (

           this.setState({showReplyForm: !this.state.showReplyForm })}>{I18n.t("comments_helper.reply_link")}

      );
    }

    return null;
  }

  renderVoteActionLinks() {
    const { comment, upVoteComment, downVoteComment } = this.props;

    if (comment.permissions.vote) {
      return (
        <div id={`comment_${comment.id}_votes`} className="comment__votes">
           upVoteComment(comment.id)} className="comment__votes--up">
            <Icon name="chevron-top" className="icon--small" ariaLabel="Votar a favor" role="img" />
            {comment.total_likes}

           downVoteComment(comment.id)} className="comment__votes--down">
            <Icon name="chevron-bottom" className="icon--small" ariaLabel="Votar en contra" role="img" />
            {comment.total_dislikes}

      );
    }

    return (
      <div id={`comment_${comment.id}_votes`} className="comment__votes">

          <Icon name="chevron-top" className="icon--small" ariaLabel="Votar a favor" role="img" />
          {comment.total_likes}

          <Icon name="chevron-bottom" className="icon--small" ariaLabel="Votar en contra" role="img" />
          {comment.total_dislikes}

    );
  }

  renderAuthorOfficialBadge() {
    const { author } = this.props.comment;
    const { official, official_level } = author;

    if (official) {
      return (

           •
          <span className={`label round level-${official_level}`}>
            {I18n.t(`officials.level_${official_level}`)}

      );
    }

    return null;
  }

  renderAlignmentBadge() {
    const { comment, commentable } = this.props;
    const { alignment } = comment;

    if (commentable.arguable && alignment !== null) {
      const cssClasses = classNames(
        'round',
        'label',
        {
          success: alignment > 0,
          alert: alignment < 0,
          secondary: alignment === 0
        }
      );
      const text =
        alignment > 0 ? I18n.t('comments.form.alignment.positive') :
        alignment < 0 ? I18n.t('comments.form.alignment.negative') :
        I18n.t('comments.form.alignment.neutral');

      return (
        {text}
      );
    }
    return null;
  }

  renderHideButton() {
    const { comment, hideComment } = this.props;
    const { id, permissions } = comment;

    if (permissions.hide) {
      return (

           |
          <DangerLink onClick={() => hideComment(id)}>
            { I18n.t('admin.actions.hide') }
          </DangerLink>

      );
    }
    return null;
  }

  renderHideAuthorButton() {
    const { comment, hideCommentAuthor } = this.props;
    const { id, permissions } = comment;

    if (permissions.hide_author) {
      return (

           |
          <DangerLink onClick={() => hideCommentAuthor(id)}>
            { I18n.t('admin.actions.hide_author') }
          </DangerLink>

      );
    }
    return null;
  }
}

export default connect(null, actions)(Comment);

Comment.propTypes = {
  comment: PropTypes.object.isRequired,
  commentable: PropTypes.object.isRequired,
  flagComment: PropTypes.func.isRequired,
  unFlagComment: PropTypes.func.isRequired,
  hideComment: PropTypes.func.isRequired,
  hideCommentAuthor: PropTypes.func.isRequired,
  upVoteComment: PropTypes.func.isRequired,
  downVoteComment: PropTypes.func.isRequired
};
<commit_msg>Highlight official comments (#709)<commit_after>import { Component, PropTypes } from 'react';
import { connect }              from 'react-redux';

import classNames               from 'classnames';

import Icon                     from '../application/icon.component';
import UserAvatar               from '../application/user_avatar.component';
import FlagActions              from '../application/flag_actions.component';
import DangerLink               from '../application/danger_link.component';

import ChildrenComments         from './children_comments.component';
import NewCommentForm           from './new_comment_form.component';

import * as actions             from './comments.actions';

import htmlToReact              from '../application/html_to_react';

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

    this.state = {
      showReplyForm: false
    };
  }

  render() {
    const { comment } = this.props;
    const { ancestry } = comment;

    if (ancestry) {
      return this.renderComment();
    } else {
      return (

          {this.renderComment()}

      );
    }
  }

  renderComment() {
    const {
      comment,
      commentable,
      flagComment,
      unFlagComment
    } = this.props;

    const { author, ancestry } = comment;

    const authorUrl = author ? `/users/${author.id}` : '#';
    const official = author ? author.official : false;

    const cssClasses = classNames(
      'comment',
      {
        'comment--nested': ancestry,
        'comment--highlight': official
      }
    );

    return (
      <article id={`comment_${comment.id}`} className={cssClasses}>

                  <UserAvatar user={author} />

                  {this.renderAuthorName()}

                <time dateTime={comment.created_at}>{' ' + comment.created_at}</time>

                  <FlagActions
                    flaggeable={comment}
                    flagAction={flagComment}
                    unFlagAction={unFlagComment}
                  />

            {this.renderAlignmentBadge()}
            {htmlToReact(comment.body)}

          <div id={`comment_${comment.id}_reply`} className="reply">
            {this.renderReplyAction()}
            {this.renderHideButton()}
            {this.renderHideAuthorButton()}
            <NewCommentForm
              commentable={commentable}
              visible={this.state.showReplyForm}
              onCommentCreated={() => this.setState({ showReplyForm: false })  }  parent={comment} />

          {this.renderVoteActionLinks()}

        <ChildrenComments comment={comment} commentable={commentable} />

    );
  }

  renderAuthorName() {
    const { author, as, administrator_id, moderator_id } = this.props.comment;

    if (author.hidden || author.erased) {
      return (
        {I18n.t("comments.comment.user_deleted")}
      );
    } else {
      if (as === 'administrator') {
        return (
          {`${I18n.t("comments.comment.admin")} #`}{administrator_id}
        );
      } else if (as === 'moderator') {
        return (
          {`${I18n.t("comments.comment.moderator")} #`}{moderator_id}
        );
      } else {
        return (
          <a href={`/users/${author.id}`}>{author.name}
        );
      }
    }
  }

  renderReplyAction() {
    const { commentable } = this.props;
    if (commentable.permissions.comment) {
      return (

           this.setState({showReplyForm: !this.state.showReplyForm })}>{I18n.t("comments_helper.reply_link")}

      );
    }

    return null;
  }

  renderVoteActionLinks() {
    const { comment, upVoteComment, downVoteComment } = this.props;

    if (comment.permissions.vote) {
      return (
        <div id={`comment_${comment.id}_votes`} className="comment__votes">
           upVoteComment(comment.id)} className="comment__votes--up">
            <Icon name="chevron-top" className="icon--small" ariaLabel="Votar a favor" role="img" />
            {comment.total_likes}

           downVoteComment(comment.id)} className="comment__votes--down">
            <Icon name="chevron-bottom" className="icon--small" ariaLabel="Votar en contra" role="img" />
            {comment.total_dislikes}

      );
    }

    return (
      <div id={`comment_${comment.id}_votes`} className="comment__votes">

          <Icon name="chevron-top" className="icon--small" ariaLabel="Votar a favor" role="img" />
          {comment.total_likes}

          <Icon name="chevron-bottom" className="icon--small" ariaLabel="Votar en contra" role="img" />
          {comment.total_dislikes}

    );
  }

  renderAuthorOfficialBadge() {
    const { author } = this.props.comment;
    const { official, official_level } = author;

    if (official) {
      return (

           •
          <span className={`label round level-${official_level}`}>
            {I18n.t(`officials.level_${official_level}`)}

      );
    }

    return null;
  }

  renderAlignmentBadge() {
    const { comment, commentable } = this.props;
    const { alignment } = comment;

    if (commentable.arguable && alignment !== null) {
      const cssClasses = classNames(
        'round',
        'label',
        {
          success: alignment > 0,
          alert: alignment < 0,
          secondary: alignment === 0
        }
      );
      const text =
        alignment > 0 ? I18n.t('comments.form.alignment.positive') :
        alignment < 0 ? I18n.t('comments.form.alignment.negative') :
        I18n.t('comments.form.alignment.neutral');

      return (
        {text}
      );
    }
    return null;
  }

  renderHideButton() {
    const { comment, hideComment } = this.props;
    const { id, permissions } = comment;

    if (permissions.hide) {
      return (

           |
          <DangerLink onClick={() => hideComment(id)}>
            { I18n.t('admin.actions.hide') }
          </DangerLink>

      );
    }
    return null;
  }

  renderHideAuthorButton() {
    const { comment, hideCommentAuthor } = this.props;
    const { id, permissions } = comment;

    if (permissions.hide_author) {
      return (

           |
          <DangerLink onClick={() => hideCommentAuthor(id)}>
            { I18n.t('admin.actions.hide_author') }
          </DangerLink>

      );
    }
    return null;
  }
}

export default connect(null, actions)(Comment);

Comment.propTypes = {
  comment: PropTypes.object.isRequired,
  commentable: PropTypes.object.isRequired,
  flagComment: PropTypes.func.isRequired,
  unFlagComment: PropTypes.func.isRequired,
  hideComment: PropTypes.func.isRequired,
  hideCommentAuthor: PropTypes.func.isRequired,
  upVoteComment: PropTypes.func.isRequired,
  downVoteComment: PropTypes.func.isRequired
};
<|endoftext|>


<commit_before>require('crypto').randomBytes(64, function (err, buff) {
  if (err) throw err
  console.log(buff.toString('hex'))
})
<commit_msg>secret script should let you require it<commit_after>// Print to stdout if called directly
if (require.main === module)
  generateSecret(function (err, secret) {
    if (err) throw err
    console.log(secret)
  })

module.exports = generateSecret

function generateSecret (cb) {
  require('crypto').randomBytes(64, function (err, buff) {
    err ? cb(err) : cb(null, buff.toString('hex'))
  })
}
<|endoftext|>


<commit_before>'use strict';

const DIR = __dirname + '/';
const DIR_ROOT = DIR + '../';
const DIR_COMMON = DIR + '../common/';

const path = require('path');
const fs = require('fs');

const cloudfunc = require(DIR_COMMON + 'cloudfunc');
const authentication = require(DIR + 'auth');
const {
    createConfig,
    configPath,
} = require(DIR + 'config');

const modulas = require(DIR + 'modulas');
const userMenu = require(DIR + 'user-menu');
const rest = require(DIR + 'rest');
const route = require(DIR + 'route');
const validate = require(DIR + 'validate');
const prefixer = require(DIR + 'prefixer');
const terminal = require(DIR + 'terminal');
const distribute = require(DIR + 'distribute');

const currify = require('currify');
const apart = require('apart');
const ponse = require('ponse');
const restafary = require('restafary');
const restbox = require('restbox');
const konsole = require('console-io');
const edward = require('edward');
const dword = require('dword');
const deepword = require('deepword');
const nomine = require('nomine');
const fileop = require('@cloudcmd/fileop');
//const readzip = require('readzip/lib/middle.js');

const isDev = process.env.NODE_ENV === 'development';
const getDist = (isDev) => isDev ? 'dist-dev' : 'dist';

const getIndexPath = (isDev) => path.join(DIR, '..', `${getDist(isDev)}/index.html`);
const html = fs.readFileSync(getIndexPath(isDev), 'utf8');

const initAuth = currify(_initAuth);
const notEmpty = (a) => a;
const clean = (a) => a.filter(notEmpty);

module.exports = (params) => {
    const p = params || {};
    const options = p.config || {};
    const config = p.configManager || createConfig({
        configPath,
    });

    const {modules} = p;

    const keys = Object.keys(options);

    for (const name of keys) {
        let value = options[name];

        if (/root/.test(name))
            validate.root(value, config);

        if (/editor|packer|columns/.test(name))
            validate[name](value);

        if (/prefix/.test(name))
            value = prefixer(value);

        config(name, value);
    }

    config('console', defaultValue(config, 'console', options));
    config('configDialog', defaultValue(config, 'configDialog', options));

    const prefixSocket = prefixer(options.prefixSocket);

    if (p.socket)
        listen({
            prefixSocket,
            config,
            socket: p.socket,
        });

    return cloudcmd({
        modules,
        config,
    });
};

module.exports.createConfigManager = createConfig;
module.exports.configPath = configPath;

module.exports._getIndexPath = getIndexPath;

function defaultValue(config, name, options) {
    const value = options[name];
    const previous = config(name);

    if (typeof value === 'undefined')
        return previous;

    return value;
}

module.exports._getPrefix = getPrefix;
function getPrefix(prefix) {
    if (typeof prefix === 'function')
        return prefix() || '';

    return prefix || '';
}

module.exports._initAuth = _initAuth;
function _initAuth(config, accept, reject, username, password) {
    if (!config('auth'))
        return accept();

    const isName = username === config('username');
    const isPass = password === config('password');

    if (isName && isPass)
        return accept();

    reject();
}

function listen({prefixSocket, socket, config}) {
    const root = apart(config, 'root');
    const auth = initAuth(config);

    prefixSocket = getPrefix(prefixSocket);
    config.listen(socket, auth);

    edward.listen(socket, {
        root,
        auth,
        prefixSocket: prefixSocket + '/edward',
    });

    dword.listen(socket, {
        root,
        auth,
        prefixSocket: prefixSocket + '/dword',
    });

    deepword.listen(socket, {
        root,
        auth,
        prefixSocket: prefixSocket + '/deepword',
    });

    config('console') && konsole.listen(socket, {
        auth,
        prefixSocket: prefixSocket + '/console',
    });

    fileop.listen(socket, {
        root,
        auth,
        prefix: prefixSocket + '/fileop',
    });

    config('terminal') && terminal(config).listen(socket, {
        auth,
        prefix: prefixSocket + '/gritty',
        command: config('terminalCommand'),
        autoRestart: config('terminalAutoRestart'),
    });

    distribute.export(config, socket);
}

function cloudcmd({modules, config}) {
    const online = apart(config, 'online');
    const cache = false;
    const diff = apart(config, 'diff');
    const zip = apart(config, 'zip');
    const root = apart(config, 'root');

    const ponseStatic = ponse.static({
        cache,
        root: DIR_ROOT,
    });

    const dropbox = config('dropbox');
    const dropboxToken = config('dropboxToken');

    const funcs = clean([
        config('console') && konsole({
            online,
        }),

        config('terminal') && terminal(config, {}),

        edward({
            root,
            online,
            diff,
            zip,
            dropbox,
            dropboxToken,
        }),

        dword({
            root,
            online,
            diff,
            zip,
            dropbox,
            dropboxToken,
        }),

        deepword({
            root,
            online,
            diff,
            zip,
            dropbox,
            dropboxToken,
        }),

        fileop(),
        nomine(),

        setUrl,
        setSW,
        logout,
        authentication(config),
        config.middle,

        modules && modulas(modules),

        config('dropbox') && restbox({
            prefix: cloudfunc.apiURL,
            root,
            token: dropboxToken,
        }),

        /*
        readzip({
            prefix: cloudfunc.apiURL + '/fs',
            root,
        }),
        */

        restafary({
            prefix: cloudfunc.apiURL + '/fs',
            root,
        }),

        userMenu({
            menuName: '.cloudcmd.menu.js',
        }),

        rest(config),
        route(config, {
            html,
        }),

        ponseStatic,
    ]);

    return funcs;
}

function logout(req, res, next) {
    if (req.url !== '/logout')
        return next();

    res.sendStatus(401);
}

module.exports._replaceDist = replaceDist;
function replaceDist(url) {
    if (!isDev)
        return url;

    return url.replace(/^\/dist\//, '/dist-dev/');
}

function setUrl(req, res, next) {
    if (/^\/cloudcmd\.js(\.map)?$/.test(req.url))
        req.url = `/dist${req.url}`;

    req.url = replaceDist(req.url);

    next();
}

function setSW(req, res, next) {
    const {url} = req;
    const isSW = /^\/sw\.js(\.map)?$/.test(url);

    if (isSW)
        req.url = replaceDist(`/dist${url}`);

    next();
}

<commit_msg>chore(cloudcmd) rm dead code<commit_after>'use strict';

const DIR = __dirname + '/';
const DIR_ROOT = DIR + '../';
const DIR_COMMON = DIR + '../common/';

const path = require('path');
const fs = require('fs');

const cloudfunc = require(DIR_COMMON + 'cloudfunc');
const authentication = require(DIR + 'auth');
const {
    createConfig,
    configPath,
} = require(DIR + 'config');

const modulas = require(DIR + 'modulas');
const userMenu = require(DIR + 'user-menu');
const rest = require(DIR + 'rest');
const route = require(DIR + 'route');
const validate = require(DIR + 'validate');
const prefixer = require(DIR + 'prefixer');
const terminal = require(DIR + 'terminal');
const distribute = require(DIR + 'distribute');

const currify = require('currify');
const apart = require('apart');
const ponse = require('ponse');
const restafary = require('restafary');
const restbox = require('restbox');
const konsole = require('console-io');
const edward = require('edward');
const dword = require('dword');
const deepword = require('deepword');
const nomine = require('nomine');
const fileop = require('@cloudcmd/fileop');

const isDev = process.env.NODE_ENV === 'development';
const getDist = (isDev) => isDev ? 'dist-dev' : 'dist';

const getIndexPath = (isDev) => path.join(DIR, '..', `${getDist(isDev)}/index.html`);
const html = fs.readFileSync(getIndexPath(isDev), 'utf8');

const initAuth = currify(_initAuth);
const notEmpty = (a) => a;
const clean = (a) => a.filter(notEmpty);

module.exports = (params) => {
    const p = params || {};
    const options = p.config || {};
    const config = p.configManager || createConfig({
        configPath,
    });

    const {modules} = p;

    const keys = Object.keys(options);

    for (const name of keys) {
        let value = options[name];

        if (/root/.test(name))
            validate.root(value, config);

        if (/editor|packer|columns/.test(name))
            validate[name](value);

        if (/prefix/.test(name))
            value = prefixer(value);

        config(name, value);
    }

    config('console', defaultValue(config, 'console', options));
    config('configDialog', defaultValue(config, 'configDialog', options));

    const prefixSocket = prefixer(options.prefixSocket);

    if (p.socket)
        listen({
            prefixSocket,
            config,
            socket: p.socket,
        });

    return cloudcmd({
        modules,
        config,
    });
};

module.exports.createConfigManager = createConfig;
module.exports.configPath = configPath;

module.exports._getIndexPath = getIndexPath;

function defaultValue(config, name, options) {
    const value = options[name];
    const previous = config(name);

    if (typeof value === 'undefined')
        return previous;

    return value;
}

module.exports._getPrefix = getPrefix;
function getPrefix(prefix) {
    if (typeof prefix === 'function')
        return prefix() || '';

    return prefix || '';
}

module.exports._initAuth = _initAuth;
function _initAuth(config, accept, reject, username, password) {
    if (!config('auth'))
        return accept();

    const isName = username === config('username');
    const isPass = password === config('password');

    if (isName && isPass)
        return accept();

    reject();
}

function listen({prefixSocket, socket, config}) {
    const root = apart(config, 'root');
    const auth = initAuth(config);

    prefixSocket = getPrefix(prefixSocket);
    config.listen(socket, auth);

    edward.listen(socket, {
        root,
        auth,
        prefixSocket: prefixSocket + '/edward',
    });

    dword.listen(socket, {
        root,
        auth,
        prefixSocket: prefixSocket + '/dword',
    });

    deepword.listen(socket, {
        root,
        auth,
        prefixSocket: prefixSocket + '/deepword',
    });

    config('console') && konsole.listen(socket, {
        auth,
        prefixSocket: prefixSocket + '/console',
    });

    fileop.listen(socket, {
        root,
        auth,
        prefix: prefixSocket + '/fileop',
    });

    config('terminal') && terminal(config).listen(socket, {
        auth,
        prefix: prefixSocket + '/gritty',
        command: config('terminalCommand'),
        autoRestart: config('terminalAutoRestart'),
    });

    distribute.export(config, socket);
}

function cloudcmd({modules, config}) {
    const online = apart(config, 'online');
    const cache = false;
    const diff = apart(config, 'diff');
    const zip = apart(config, 'zip');
    const root = apart(config, 'root');

    const ponseStatic = ponse.static({
        cache,
        root: DIR_ROOT,
    });

    const dropbox = config('dropbox');
    const dropboxToken = config('dropboxToken');

    const funcs = clean([
        config('console') && konsole({
            online,
        }),

        config('terminal') && terminal(config, {}),

        edward({
            root,
            online,
            diff,
            zip,
            dropbox,
            dropboxToken,
        }),

        dword({
            root,
            online,
            diff,
            zip,
            dropbox,
            dropboxToken,
        }),

        deepword({
            root,
            online,
            diff,
            zip,
            dropbox,
            dropboxToken,
        }),

        fileop(),
        nomine(),

        setUrl,
        setSW,
        logout,
        authentication(config),
        config.middle,

        modules && modulas(modules),

        config('dropbox') && restbox({
            prefix: cloudfunc.apiURL,
            root,
            token: dropboxToken,
        }),

        restafary({
            prefix: cloudfunc.apiURL + '/fs',
            root,
        }),

        userMenu({
            menuName: '.cloudcmd.menu.js',
        }),

        rest(config),
        route(config, {
            html,
        }),

        ponseStatic,
    ]);

    return funcs;
}

function logout(req, res, next) {
    if (req.url !== '/logout')
        return next();

    res.sendStatus(401);
}

module.exports._replaceDist = replaceDist;
function replaceDist(url) {
    if (!isDev)
        return url;

    return url.replace(/^\/dist\//, '/dist-dev/');
}

function setUrl(req, res, next) {
    if (/^\/cloudcmd\.js(\.map)?$/.test(req.url))
        req.url = `/dist${req.url}`;

    req.url = replaceDist(req.url);

    next();
}

function setSW(req, res, next) {
    const {url} = req;
    const isSW = /^\/sw\.js(\.map)?$/.test(url);

    if (isSW)
        req.url = replaceDist(`/dist${url}`);

    next();
}

<|endoftext|>


<commit_before>/**
 * Created by  on 1/20/2017.
 */

function findCloseMosque(agent) {
    var minDistance = 99999;
    var closeMosque;
    for (var i = 0; i < mosques.length; i++) {
        var mosque = mosques[i];
        var distance  = Math.sqrt(Math.pow(mosque.x-agent.x,2) +  Math.pow(mosque.y-agent.y,2));
        if (distance < minDistance){
            minDistance = distance;
            closeMosque = mosque
        }
    }
    //for (var i = 0; i < exists.length; i++) {
    //    var exist = exists[i];
    //    var distance  = Math.sqrt(Math.pow(exist.x-agent.x,2) +  Math.pow(exist.y-agent.y,2));
    //    if (distance < minDistance){
    //        minDistance = distance;
    //        closeMosque = exist
    //    }
    //}
    return closeMosque;

}

function isInRange(agent){
    var treshhold =300;
      var mosque  = findCloseMosque(agent);
    if(mosque) {
        var distance = Math.sqrt(Math.pow(mosque.x - agent.x, 2) + Math.pow(mosque.y - agent.y, 2));
        if (distance < treshhold) {
            return mosque;
        }
    }
    return null;

}

<commit_msg>better thresholds<commit_after>/**
 * Created by  on 1/20/2017.
 */

function findCloseMosque(agent) {
    var minDistance = 99999;
    var closeMosque;
    for (var i = 0; i < mosques.length; i++) {
        var mosque = mosques[i];
        var distance  = Math.sqrt(Math.pow(mosque.x-agent.x,2) +  Math.pow(mosque.y-agent.y,2));
        if (distance < minDistance){
            minDistance = distance;
            closeMosque = mosque
        }
    }
    //for (var i = 0; i < exists.length; i++) {
    //    var exist = exists[i];
    //    var distance  = Math.sqrt(Math.pow(exist.x-agent.x,2) +  Math.pow(exist.y-agent.y,2));
    //    if (distance < minDistance){
    //        minDistance = distance;
    //        closeMosque = exist
    //    }
    //}
    return closeMosque;

}

function isInRange(agent){
    var treshhold;
      var mosque  = findCloseMosque(agent);

    if(mosque) {
        if (mosque.key == "mosque1"){
            treshhold = 100;
        }
        if (mosque.key == "mosque2"){
            treshhold = 200;
        }

        var distance = Math.sqrt(Math.pow(mosque.x - agent.x, 2) + Math.pow(mosque.y - agent.y, 2));
        if (distance < treshhold) {
            return mosque;
        }
    }
    return null;

}

<|endoftext|>


<commit_before>import webpack from "webpack"
import path from "path"
import mkdirp from "mkdirp"
import fs from "fs"
import ExtractTextPlugin from "extract-text-webpack-plugin"
import ChunkManifestPlugin from "chunk-manifest-webpack-plugin"
import StatsPlugin from "webpack-stats-plugin"
import callerDependency from "./callerDependency"
import serverSideHotModuleReload from "./serverSideHotModuleReload"

// commented out to please eslint, but re-add if logging is needed in this file.
// import {logging} from "react-server"
// const logger = logging.getLogger(__LOGGER__);

// compiles the routes file for browser clients using webpack.
// returns a tuple of { compiler, serverRoutes }. compiler is a webpack compiler
// that is ready to have run called, and serverRoutes is a promise that resolve to
// a path to the transpiled server routes file path. The promise only resolves
// once the compiler has been run. The file path returned from the promise
// can be required and passed in to reactServer.middleware().
// TODO: add options for sourcemaps.
export default (opts = {}) => {
	const {
		routes,
		webpackConfig,
		workingDir = "./__clientTemp",
		routesDir = ".",
		outputDir = workingDir + "/build",
		outputUrl = "/static/",
		hot = true,
		minify = false,
		stats = false,
		longTermCaching = false,
	} = opts;

	// support legacy webpack configuration name
	const webpackConfiguration = webpackConfig || opts['webpack-config'];
	if (longTermCaching && hot) {
		// chunk hashes can't be used in hot mode, so we can't use long-term caching
		// and hot mode at the same time.
		throw new Error("Hot reload cannot be used with long-term caching. Please disable either long-term caching or hot reload.");
	}

	var webpackConfigFunc = (data) => { return data }
	if (webpackConfiguration) {
		const webpackDirAbsolute = path.resolve(process.cwd(), webpackConfiguration);
		const userWebpackConfigFunc = require(webpackDirAbsolute)
		webpackConfigFunc = userWebpackConfigFunc.default
	}

	const workingDirAbsolute = path.resolve(process.cwd(), workingDir);
	mkdirp.sync(workingDirAbsolute);
	const outputDirAbsolute = path.resolve(process.cwd(), outputDir);
	mkdirp.sync(outputDirAbsolute);

	const routesDirAbsolute = path.resolve(process.cwd(), routesDir);

	// for each route, let's create an entrypoint file that includes the page file and the routes file
	let bootstrapFile = writeClientBootstrapFile(workingDirAbsolute, opts);
	const entrypointBase = hot ? [
		require.resolve("webpack-dev-server/client") + "?" + outputUrl,
		require.resolve("webpack/hot/only-dev-server"),
	] : [];
	let entrypoints = {};
	for (let routeName of Object.keys(routes.routes)) {
		let route = routes.routes[routeName];
		let formats = normalizeRoutesPage(route.page);
		for (let format of Object.keys(formats)) {
			const absolutePathToPage = require.resolve(path.resolve(routesDirAbsolute, formats[format]));

			entrypoints[`${routeName}${format !== "default" ? "-" + format : ""}`] = [
				...entrypointBase,
				bootstrapFile,
				absolutePathToPage,
			];
		}
	}

	// now rewrite the routes file out in a webpack-compatible way.
	writeWebpackCompatibleRoutesFile(routes, routesDir, workingDirAbsolute, null, true);

	// finally, let's pack this up with webpack.
	const compiler = webpack(webpackConfigFunc(packageCodeForBrowser(entrypoints, outputDirAbsolute, outputUrl, hot, minify, longTermCaching, stats)));

	const serverRoutes = new Promise((resolve) => {
		compiler.plugin("done", (stats) => {
			const manifest = statsToManifest(stats);
			fs.writeFileSync(path.join(outputDir, "manifest.json"), JSON.stringify(manifest));

			// this file is generated by the build in non-hot mode, but we don't need
			// it (we got the data ourselves from stats in statsToManifest()).
			if (!hot) {
				fs.unlinkSync(path.join(outputDir, "chunk-manifest.json"));
			}

			const routesFilePath = writeWebpackCompatibleRoutesFile(routes, routesDir, workingDirAbsolute, outputUrl, false, manifest);

			if (hot) {
				serverSideHotModuleReload(stats);
			}

			resolve(routesFilePath);
		});
	});

	return {
		serverRoutes,
		compiler,
	};
}

// takes in the stats object from a successful compilation and returns a manifest
// object that characterizes the results of the compilation for CSS/JS loading
// and integrity checking. the manifest has the following entries:
//   jsChunksByName: an object that maps chunk names to their JS entrypoint file.
//   cssChunksByName: an object that maps chunk names to their CSS file. Note that
//     not all named chunks necessarily have a CSS file, so not all names will
//     show up as a key in this object.
//   jsChunksById: an object that maps chunk ids to their JS entrypoint file.
//   hash: the overall hash of the build, which can be used to check integrity
//     with prebuilt sources.
function statsToManifest(stats) {
	const jsChunksByName = {};
	const cssChunksByName = {};
	const jsChunksById = {};
	for (const chunk of stats.compilation.chunks) {
		if (chunk.name) {
			jsChunksByName[chunk.name] = chunk.files[0];

			for (let i = 1; i < chunk.files.length; i++) {
				if (/\.css$/.test(chunk.files[i])) {
					// the CSS file is probably last file in the array, unless there have been hot updates for the JS
					// which show up in the array prior to the CSS file.
					cssChunksByName[chunk.name] = chunk.files[i];
					break;
				}
			}
		}
		jsChunksById[chunk.id] = chunk.files[0];
	}
	return {
		jsChunksByName,
		jsChunksById,
		cssChunksByName,
		hash: stats.hash,
	};
}

function packageCodeForBrowser(entrypoints, outputDir, outputUrl, hot, minify, longTermCaching, stats) {
	const NonCachingExtractTextLoader = path.join(__dirname, "./NonCachingExtractTextLoader");
	const extractTextLoader = require.resolve(NonCachingExtractTextLoader) + "?{remove:true}!css-loader";
	let webpackConfig = {
		entry: entrypoints,
		output: {
			path: outputDir,
			// other than hot mode, the public path is set at runtime.
			publicPath: hot ? outputUrl : undefined,
			filename: `[name]${longTermCaching ? ".[chunkhash]" : ""}.bundle.js`,
			chunkFilename: `[id]${longTermCaching ? ".[chunkhash]" : ""}.bundle.js`,
		},
		module: {
			loaders: [
				{
					test: /\.jsx?$/,
					loader: "babel",
					exclude: /node_modules/,
				},
				{
					test: /\.css$/,
					loader: extractTextLoader,
					exclude: /node_modules/,
				},
				{
					test: /\.(eot|woff|woff2|ttf|ttc|png|svg|jpg|jpeg|gif|cgm|tiff|webp|bmp|ico)$/i,
					loader: "file",
					exclude: /node_modules/,
				},
				{
					test: /\.json/,
					loader: "json",
					// exclude: /node_modules/,
				},
				{
					test: /\.less/,
					loader: extractTextLoader + "!less-loader",
					exclude: /node_modules/,
				},
				{
					test: /\.s(a|c)ss$/,
					loader: extractTextLoader + "!sass-loader",
					exclude: /node_modules/,
				},
				{
					test: /\.md/,
					loader: "raw",
					exclude: /node_modules/,
				},
			],
		},
		resolve: {
			alias: {
				// These need to be singletons.
				"react"        : callerDependency("react"),
				"react-server" : callerDependency("react-server"),
			},
		},
		resolveLoader: {
			root: [
				path.resolve(path.join(path.dirname(require.resolve("webpack")), "../..")),
			],
		},
		plugins: [
			new ChunkManifestPlugin({
				filename: "chunk-manifest.json",
				manifestVariable: "webpackManifest",
			}),
			new ExtractTextPlugin(`[name]${longTermCaching ? ".[chunkhash]" : ""}.css`),
			new webpack.optimize.CommonsChunkPlugin({
				name:"common",
			}),
		],
	};

	if (stats) {
		webpackConfig.plugins.push(new StatsPlugin.StatsWriterPlugin({
			fields: ["assets", "assetsByChunkName", "chunks", "errors", "warnings", "version", "hash", "time", "filteredModules", "children", "modules"],
		}));
	}

	if (minify) {
		webpackConfig.plugins = [
			...webpackConfig.plugins,
			new webpack.DefinePlugin({
				'process.env': {NODE_ENV: '"production"'},
			}),
			// TODO: should this be done as babel plugin?
			new webpack.optimize.UglifyJsPlugin(),
		];
	} else {
		webpackConfig.plugins.push(new webpack.SourceMapDevToolPlugin());
	}

	if (hot) {
		webpackConfig.module.loaders = [
			{
				test: /\.jsx?$/,
				loader: "react-hot",
				exclude: /node_modules/,
			},
			...webpackConfig.module.loaders,
		];
		webpackConfig.plugins = [
			...webpackConfig.plugins,
			new webpack.HotModuleReplacementPlugin(),
			new webpack.NoErrorsPlugin(),
		];
	}

	if (longTermCaching) {
		webpackConfig.plugins = [
			new webpack.optimize.OccurenceOrderPlugin(),
			...webpackConfig.plugins,
		];
	}

	return webpackConfig;
}

// writes out a routes file that can be used at runtime.
function writeWebpackCompatibleRoutesFile(routes, routesDir, workingDirAbsolute, staticUrl, isClient, manifest) {
	let routesOutput = [];

	const coreMiddleware = require.resolve("react-server-core-middleware");
	const existingMiddleware = routes.middleware ? routes.middleware.map((middlewareRelativePath) => {
		return `unwrapEs6Module(require("${path.relative(workingDirAbsolute, path.resolve(routesDir, middlewareRelativePath))}"))`
	}) : [];
	routesOutput.push(`
var manifest = ${manifest ? JSON.stringify(manifest) : "undefined"};
function unwrapEs6Module(module) { return module.__esModule ? module.default : module }
var coreJsMiddleware = require('${coreMiddleware}').coreJsMiddleware;
var coreCssMiddleware = require('${coreMiddleware}').coreCssMiddleware;
module.exports = {
	middleware:[
		coreJsMiddleware(${JSON.stringify(staticUrl)}, manifest),
		coreCssMiddleware(${JSON.stringify(staticUrl)}, manifest),
		${existingMiddleware.join(",")}
	],
	routes:{`);

	for (let routeName of Object.keys(routes.routes)) {
		let route = routes.routes[routeName];

		// On the line below specifying 'method', if the route doesn't have a method, we'll assume it's [] so that
		// routr passes through and matches any method
		// https://github.com/yahoo/routr/blob/v2.1.0/lib/router.js#L49-L57
		let method = route.method;

		// Safely check for an empty object, array, or string and specifically set it to 'undefined'
		if (method === undefined || method === null || method === {} || method.length === 0) {
			method = undefined; // 'undefined' is the value that routr needs to accept any method
		}

		routesOutput.push(`
		${routeName}: {
			path: ${JSON.stringify(route.path)},
			method: ${JSON.stringify(method)},`);

		let formats = normalizeRoutesPage(route.page);
		routesOutput.push(`
			page: {`);
		for (let format of Object.keys(formats)) {
			const formatModule = formats[format];
			var relativePathToPage = path.relative(workingDirAbsolute, path.resolve(routesDir, formatModule));
			routesOutput.push(`
				${format}: function() {
					return {
						done: function(cb) {`);
			if (isClient) {
				routesOutput.push(`
							require.ensure("${relativePathToPage}", function() {
								cb(unwrapEs6Module(require("${relativePathToPage}")));
							});`);
			} else {
				routesOutput.push(`
							try {
								cb(unwrapEs6Module(require("${relativePathToPage}")));
							} catch (e) {
								console.error('Failed to load page at "${relativePathToPage}"', e.stack);
							}`);
			}
			routesOutput.push(`
						}
					};
				},`);
		}
		routesOutput.push(`
			},
		},`);
	}
	routesOutput.push(`
	}
};`);

	const routesContent = routesOutput.join("");
	// make a unique file name so that when it is required, there are no collisions
	// in the module loader between different invocations.
	const routesFilePath = `${workingDirAbsolute}/routes_${isClient ? "client" : "server"}.js`;
	fs.writeFileSync(routesFilePath, routesContent);

	return routesFilePath;
}

// the page value for routes.routes["SomeRoute"] can either be a string for the default
// module name or an object mapping format names to module names. This method normalizes
// the value to an object.
function normalizeRoutesPage(page) {
	if (typeof page === "string") {
		return {default: page};
	}
	return page;
}

// writes out a bootstrap file for the client which in turn includes the client
// routes file. note that outputDir must be the same directory as the client routes
// file, which must be named "routes_client".
function writeClientBootstrapFile(outputDir, opts) {
	var outputFile = outputDir + "/entry.js";
	fs.writeFileSync(outputFile, `
		if (typeof window !== "undefined") {
			window.__setReactServerBase = function(path) {
				// according to http://webpack.github.io/docs/configuration.html#output-publicpath
				// we should never set __webpack_public_path__ when hot module replacement is on.
				if (!module.hot) {
					__webpack_public_path__ = path;
				}
				window.__reactServerBase = path;
			}
		}
		var reactServer = require("react-server");
		window.rfBootstrap = function() {
			reactServer.logging.setLevel('main',  ${JSON.stringify(opts.logLevel)});
			reactServer.logging.setLevel('time',  ${JSON.stringify(opts.timingLogLevel)});
			reactServer.logging.setLevel('gauge', ${JSON.stringify(opts.gaugeLogLevel)});
			new reactServer.ClientController({routes: require("./routes_client")}).init();
		}`
	);
	return outputFile;
}
<commit_msg>Fix comment.<commit_after>import webpack from "webpack"
import path from "path"
import mkdirp from "mkdirp"
import fs from "fs"
import ExtractTextPlugin from "extract-text-webpack-plugin"
import ChunkManifestPlugin from "chunk-manifest-webpack-plugin"
import StatsPlugin from "webpack-stats-plugin"
import callerDependency from "./callerDependency"
import serverSideHotModuleReload from "./serverSideHotModuleReload"

// commented out to please eslint, but re-add if logging is needed in this file.
// import {logging} from "react-server"
// const logger = logging.getLogger(__LOGGER__);

// compiles the routes file for browser clients using webpack.
// returns a tuple of { compiler, serverRoutes }. compiler is a webpack compiler
// that is ready to have run called, and serverRoutes is a promise that resolve to
// a path to the transpiled server routes file path. The promise only resolves
// once the compiler has been run. The file path returned from the promise
// can be required and passed in to reactServer.middleware().
// TODO: add options for sourcemaps.
export default (opts = {}) => {
	const {
		routes,
		webpackConfig,
		workingDir = "./__clientTemp",
		routesDir = ".",
		outputDir = workingDir + "/build",
		outputUrl = "/static/",
		hot = true,
		minify = false,
		stats = false,
		longTermCaching = false,
	} = opts;

	// support legacy webpack configuration name
	const webpackConfiguration = webpackConfig || opts['webpack-config'];
	if (longTermCaching && hot) {
		// chunk hashes can't be used in hot mode, so we can't use long-term caching
		// and hot mode at the same time.
		throw new Error("Hot reload cannot be used with long-term caching. Please disable either long-term caching or hot reload.");
	}

	var webpackConfigFunc = (data) => { return data }
	if (webpackConfiguration) {
		const webpackDirAbsolute = path.resolve(process.cwd(), webpackConfiguration);
		const userWebpackConfigFunc = require(webpackDirAbsolute)
		webpackConfigFunc = userWebpackConfigFunc.default
	}

	const workingDirAbsolute = path.resolve(process.cwd(), workingDir);
	mkdirp.sync(workingDirAbsolute);
	const outputDirAbsolute = path.resolve(process.cwd(), outputDir);
	mkdirp.sync(outputDirAbsolute);

	const routesDirAbsolute = path.resolve(process.cwd(), routesDir);

	// for each route, let's create an entrypoint file that includes the page file and the routes file
	let bootstrapFile = writeClientBootstrapFile(workingDirAbsolute, opts);
	const entrypointBase = hot ? [
		require.resolve("webpack-dev-server/client") + "?" + outputUrl,
		require.resolve("webpack/hot/only-dev-server"),
	] : [];
	let entrypoints = {};
	for (let routeName of Object.keys(routes.routes)) {
		let route = routes.routes[routeName];
		let formats = normalizeRoutesPage(route.page);
		for (let format of Object.keys(formats)) {
			const absolutePathToPage = require.resolve(path.resolve(routesDirAbsolute, formats[format]));

			entrypoints[`${routeName}${format !== "default" ? "-" + format : ""}`] = [
				...entrypointBase,
				bootstrapFile,
				absolutePathToPage,
			];
		}
	}

	// now rewrite the routes file out in a webpack-compatible way.
	writeWebpackCompatibleRoutesFile(routes, routesDir, workingDirAbsolute, null, true);

	// finally, let's pack this up with webpack.
	const compiler = webpack(webpackConfigFunc(packageCodeForBrowser(entrypoints, outputDirAbsolute, outputUrl, hot, minify, longTermCaching, stats)));

	const serverRoutes = new Promise((resolve) => {
		compiler.plugin("done", (stats) => {
			const manifest = statsToManifest(stats);
			fs.writeFileSync(path.join(outputDir, "manifest.json"), JSON.stringify(manifest));

			// this file is generated by the build in non-hot mode, but we don't need
			// it (we got the data ourselves from stats in statsToManifest()).
			if (!hot) {
				fs.unlinkSync(path.join(outputDir, "chunk-manifest.json"));
			}

			const routesFilePath = writeWebpackCompatibleRoutesFile(routes, routesDir, workingDirAbsolute, outputUrl, false, manifest);

			if (hot) {
				serverSideHotModuleReload(stats);
			}

			resolve(routesFilePath);
		});
	});

	return {
		serverRoutes,
		compiler,
	};
}

// takes in the stats object from a successful compilation and returns a manifest
// object that characterizes the results of the compilation for CSS/JS loading
// and integrity checking. the manifest has the following entries:
//   jsChunksByName: an object that maps chunk names to their JS entrypoint file.
//   cssChunksByName: an object that maps chunk names to their CSS file. Note that
//     not all named chunks necessarily have a CSS file, so not all names will
//     show up as a key in this object.
//   jsChunksById: an object that maps chunk ids to their JS entrypoint file.
//   hash: the overall hash of the build, which can be used to check integrity
//     with prebuilt sources.
function statsToManifest(stats) {
	const jsChunksByName = {};
	const cssChunksByName = {};
	const jsChunksById = {};
	for (const chunk of stats.compilation.chunks) {
		if (chunk.name) {
			jsChunksByName[chunk.name] = chunk.files[0];

			for (let i = 1; i < chunk.files.length; i++) {
				if (/\.css$/.test(chunk.files[i])) {
					// the CSS file is probably last file in the array, unless there have been hot updates for the JS
					// which show up in the array prior to the CSS file.
					cssChunksByName[chunk.name] = chunk.files[i];
					break;
				}
			}
		}
		jsChunksById[chunk.id] = chunk.files[0];
	}
	return {
		jsChunksByName,
		jsChunksById,
		cssChunksByName,
		hash: stats.hash,
	};
}

function packageCodeForBrowser(entrypoints, outputDir, outputUrl, hot, minify, longTermCaching, stats) {
	const NonCachingExtractTextLoader = path.join(__dirname, "./NonCachingExtractTextLoader");
	const extractTextLoader = require.resolve(NonCachingExtractTextLoader) + "?{remove:true}!css-loader";
	let webpackConfig = {
		entry: entrypoints,
		output: {
			path: outputDir,
			// other than hot mode, the public path is set at runtime.
			publicPath: hot ? outputUrl : undefined,
			filename: `[name]${longTermCaching ? ".[chunkhash]" : ""}.bundle.js`,
			chunkFilename: `[id]${longTermCaching ? ".[chunkhash]" : ""}.bundle.js`,
		},
		module: {
			loaders: [
				{
					test: /\.jsx?$/,
					loader: "babel",
					exclude: /node_modules/,
				},
				{
					test: /\.css$/,
					loader: extractTextLoader,
					exclude: /node_modules/,
				},
				{
					test: /\.(eot|woff|woff2|ttf|ttc|png|svg|jpg|jpeg|gif|cgm|tiff|webp|bmp|ico)$/i,
					loader: "file",
					exclude: /node_modules/,
				},
				{
					test: /\.json/,
					loader: "json",
					// exclude: /node_modules/,
				},
				{
					test: /\.less/,
					loader: extractTextLoader + "!less-loader",
					exclude: /node_modules/,
				},
				{
					test: /\.s(a|c)ss$/,
					loader: extractTextLoader + "!sass-loader",
					exclude: /node_modules/,
				},
				{
					test: /\.md/,
					loader: "raw",
					exclude: /node_modules/,
				},
			],
		},
		resolve: {
			alias: {
				// These need to be singletons.
				"react"        : callerDependency("react"),
				"react-server" : callerDependency("react-server"),
			},
		},
		resolveLoader: {
			root: [
				path.resolve(path.join(path.dirname(require.resolve("webpack")), "../..")),
			],
		},
		plugins: [
			new ChunkManifestPlugin({
				filename: "chunk-manifest.json",
				manifestVariable: "webpackManifest",
			}),
			new ExtractTextPlugin(`[name]${longTermCaching ? ".[chunkhash]" : ""}.css`),
			new webpack.optimize.CommonsChunkPlugin({
				name:"common",
			}),
		],
	};

	if (stats) {
		webpackConfig.plugins.push(new StatsPlugin.StatsWriterPlugin({
			fields: ["assets", "assetsByChunkName", "chunks", "errors", "warnings", "version", "hash", "time", "filteredModules", "children", "modules"],
		}));
	}

	if (minify) {
		webpackConfig.plugins = [
			...webpackConfig.plugins,
			new webpack.DefinePlugin({
				'process.env': {NODE_ENV: '"production"'},
			}),
			// TODO: should this be done as babel plugin?
			new webpack.optimize.UglifyJsPlugin(),
		];
	} else {
		webpackConfig.plugins.push(new webpack.SourceMapDevToolPlugin());
	}

	if (hot) {
		webpackConfig.module.loaders = [
			{
				test: /\.jsx?$/,
				loader: "react-hot",
				exclude: /node_modules/,
			},
			...webpackConfig.module.loaders,
		];
		webpackConfig.plugins = [
			...webpackConfig.plugins,
			new webpack.HotModuleReplacementPlugin(),
			new webpack.NoErrorsPlugin(),
		];
	}

	if (longTermCaching) {
		webpackConfig.plugins = [
			new webpack.optimize.OccurenceOrderPlugin(),
			...webpackConfig.plugins,
		];
	}

	return webpackConfig;
}

// writes out a routes file that can be used at runtime.
function writeWebpackCompatibleRoutesFile(routes, routesDir, workingDirAbsolute, staticUrl, isClient, manifest) {
	let routesOutput = [];

	const coreMiddleware = require.resolve("react-server-core-middleware");
	const existingMiddleware = routes.middleware ? routes.middleware.map((middlewareRelativePath) => {
		return `unwrapEs6Module(require("${path.relative(workingDirAbsolute, path.resolve(routesDir, middlewareRelativePath))}"))`
	}) : [];
	routesOutput.push(`
var manifest = ${manifest ? JSON.stringify(manifest) : "undefined"};
function unwrapEs6Module(module) { return module.__esModule ? module.default : module }
var coreJsMiddleware = require('${coreMiddleware}').coreJsMiddleware;
var coreCssMiddleware = require('${coreMiddleware}').coreCssMiddleware;
module.exports = {
	middleware:[
		coreJsMiddleware(${JSON.stringify(staticUrl)}, manifest),
		coreCssMiddleware(${JSON.stringify(staticUrl)}, manifest),
		${existingMiddleware.join(",")}
	],
	routes:{`);

	for (let routeName of Object.keys(routes.routes)) {
		let route = routes.routes[routeName];

		// On the line below specifying 'method', if the route doesn't have a method, we'll set it to `undefined` so that
		// routr passes through and matches any method
		// https://github.com/yahoo/routr/blob/v2.1.0/lib/router.js#L49-L57
		let method = route.method;

		// Safely check for an empty object, array, or string and specifically set it to 'undefined'
		if (method === undefined || method === null || method === {} || method.length === 0) {
			method = undefined; // 'undefined' is the value that routr needs to accept any method
		}

		routesOutput.push(`
		${routeName}: {
			path: ${JSON.stringify(route.path)},
			method: ${JSON.stringify(method)},`);

		let formats = normalizeRoutesPage(route.page);
		routesOutput.push(`
			page: {`);
		for (let format of Object.keys(formats)) {
			const formatModule = formats[format];
			var relativePathToPage = path.relative(workingDirAbsolute, path.resolve(routesDir, formatModule));
			routesOutput.push(`
				${format}: function() {
					return {
						done: function(cb) {`);
			if (isClient) {
				routesOutput.push(`
							require.ensure("${relativePathToPage}", function() {
								cb(unwrapEs6Module(require("${relativePathToPage}")));
							});`);
			} else {
				routesOutput.push(`
							try {
								cb(unwrapEs6Module(require("${relativePathToPage}")));
							} catch (e) {
								console.error('Failed to load page at "${relativePathToPage}"', e.stack);
							}`);
			}
			routesOutput.push(`
						}
					};
				},`);
		}
		routesOutput.push(`
			},
		},`);
	}
	routesOutput.push(`
	}
};`);

	const routesContent = routesOutput.join("");
	// make a unique file name so that when it is required, there are no collisions
	// in the module loader between different invocations.
	const routesFilePath = `${workingDirAbsolute}/routes_${isClient ? "client" : "server"}.js`;
	fs.writeFileSync(routesFilePath, routesContent);

	return routesFilePath;
}

// the page value for routes.routes["SomeRoute"] can either be a string for the default
// module name or an object mapping format names to module names. This method normalizes
// the value to an object.
function normalizeRoutesPage(page) {
	if (typeof page === "string") {
		return {default: page};
	}
	return page;
}

// writes out a bootstrap file for the client which in turn includes the client
// routes file. note that outputDir must be the same directory as the client routes
// file, which must be named "routes_client".
function writeClientBootstrapFile(outputDir, opts) {
	var outputFile = outputDir + "/entry.js";
	fs.writeFileSync(outputFile, `
		if (typeof window !== "undefined") {
			window.__setReactServerBase = function(path) {
				// according to http://webpack.github.io/docs/configuration.html#output-publicpath
				// we should never set __webpack_public_path__ when hot module replacement is on.
				if (!module.hot) {
					__webpack_public_path__ = path;
				}
				window.__reactServerBase = path;
			}
		}
		var reactServer = require("react-server");
		window.rfBootstrap = function() {
			reactServer.logging.setLevel('main',  ${JSON.stringify(opts.logLevel)});
			reactServer.logging.setLevel('time',  ${JSON.stringify(opts.timingLogLevel)});
			reactServer.logging.setLevel('gauge', ${JSON.stringify(opts.gaugeLogLevel)});
			new reactServer.ClientController({routes: require("./routes_client")}).init();
		}`
	);
	return outputFile;
}
<|endoftext|>