<commit_before>'use strict';

var utils = require('loader-utils');
var sass = require('node-sass');
var path = require('path');
var os = require('os');
var fs = require('fs');

// A typical sass error looks like this
var SassError = {
    message: 'invalid property name',
    column: 14,
    line: 1,
    file: 'stdin',
    status: 1
};

var extPrecedence = ['.scss', '.sass', '.css'];
var matchCss = /\.css$/;

/**
 * The sass-loader makes node-sass available to webpack modules.
 *
 * @param {string} content
 * @returns {*}
 */
module.exports = function (content) {
    var callback = this.async();
    var isSync = typeof callback !== 'function';
    var self = this;
    var resourcePath = this.resourcePath;
    var result;
    var opt;

    /**
     * Enhances the sass error with additional information about what actually went wrong.
     *
     * @param {SassError} err
     */
    function formatSassError(err) {
        var msg = err.message;

        if (err.file === 'stdin') {
            err.file = resourcePath;
        }
        // node-sass returns UNIX-style paths
        err.file = path.normalize(err.file);

        // The 'Current dir' hint of node-sass does not help us, we're providing
        // additional information by reading the err.file property
        msg = msg.replace(/\s*Current dir:\s*/, '');

        err.message = getFileExcerptIfPossible(err) +
            msg.charAt(0).toUpperCase() + msg.slice(1) + os.EOL +
            '      in ' + err.file + ' (line ' + err.line + ', column ' + err.column + ')';

        // Instruct webpack to hide the JS stack from the console
        // Usually you're only interested in the SASS stack in this case.
        err.hideStack = true;
    }

    /**
     * Returns an importer that uses webpack's resolving algorithm.
     *
     * It's important that the returned function has the correct number of arguments
     * (based on whether the call is sync or async) because otherwise node-sass doesn't exit.
     *
     * @returns {function}
     */
    function getWebpackImporter() {
        if (isSync) {
            return function syncWebpackImporter(url, context) {
                url = utils.urlToRequest(url, opt.root);
                context = normalizeContext(context);

                return syncResolve(context, url, getImportsToResolve(url));
            };
        }
        return function asyncWebpackImporter(url, context, done) {
            url = utils.urlToRequest(url, opt.root);
            context = normalizeContext(context);

            asyncResolve(context, url, getImportsToResolve(url), done);
        };
    }

    /**
     * Tries to resolve the given url synchronously. If a resolve error occurs, a second try for the same
     * module prefixed with an underscore is started.
     *
     * @param {object} loaderContext
     * @param {string} url
     //* @param {string} context
     * @returns {object}
     */
    function syncResolve(fileContext, originalImport, importsToResolve) {
        var importToResolve = importsToResolve.shift();
        var resolvedFilename;

        if (!importToResolve) {
            return {
                file: originalImport
            };
        }

        try {
            resolvedFilename = self.resolveSync(fileContext, importToResolve);
            resolvedFilename = resolvedFilename.replace(matchCss, '');
            return {
                file: resolvedFilename
            };
        } catch (err) {
            return syncResolve(fileContext, originalImport, importsToResolve);
        }
    }

    /**
     * Tries to resolve the given url asynchronously. If a resolve error occurs, a second try for the same
     * module prefixed with an underscore is started.
     *
     * @param {object} loaderContext
     * @param {string} url
     * @param {string} fileContext
     * @param {function} done
     */
    function asyncResolve(fileContext, originalImport, importsToResolve, done) {
        var importToResolve = importsToResolve.shift();

        if (!importToResolve) {
            done({
                file: originalImport
            });
            return;
        }

        self.resolve(fileContext, importToResolve, function onWebpackResolve(err, resolvedFilename) {
            if (err) {
                asyncResolve(fileContext, originalImport, importsToResolve, done);
                return;
            }
            // Use self.loadModule() before calling done() to make imported files available to
            // other webpack tools like postLoaders etc.?

            resolvedFilename = resolvedFilename.replace(matchCss, '');
            done({
                file: resolvedFilename.replace(matchCss, '')
            });
        });
    }

    function normalizeContext(context) {
        // The first file is 'stdin' when we're using the data option
        if (context === 'stdin') {
            context = resourcePath;
        }
        return path.dirname(context);
    }

    // When files have been imported via the includePaths-option, these files need to be
    // introduced to webpack in order to make them watchable.
    function addIncludedFilesToWebpack(includedFiles) {
        includedFiles.forEach(addNormalizedDependency);
    }

    function addNormalizedDependency(file) {
        // node-sass returns UNIX-style paths
        self.dependency(path.normalize(file));
    }

    this.cacheable();

    opt = utils.parseQuery(this.query);
    opt.data = content;

    // Skip empty files, otherwise it will stop webpack, see issue #21
    if (opt.data.trim() === '') {
        return callback(null, content);
    }

    // opt.outputStyle
    if (!opt.outputStyle && this.minimize) {
        opt.outputStyle = 'compressed';
    }

    // opt.sourceMap
    // Not using the `this.sourceMap` flag because css source maps are different
    // @see https://github.com/webpack/css-loader/pull/40
    if (opt.sourceMap) {
        // deliberately overriding the sourceMap option
        // this value is (currently) ignored by libsass when using the data input instead of file input
        // however, it is still necessary for correct relative paths in result.map.sources
        opt.sourceMap = this.options.output.path + '/sass.map';
        opt.omitSourceMapUrl = true;

        // If sourceMapContents option is not set, set it to true otherwise maps will be empty/null
        // when exported by webpack-extract-text-plugin.
        if ('sourceMapContents' in opt === false) {
            opt.sourceMapContents = true;
        }
    }

    // indentedSyntax is a boolean flag
    opt.indentedSyntax = Boolean(opt.indentedSyntax);

    // opt.importer
    opt.importer = getWebpackImporter();

    // start the actual rendering
    if (isSync) {
        try {
            result = sass.renderSync(opt);
            addIncludedFilesToWebpack(result.stats.includedFiles);
            return result.css.toString();
        } catch (err) {
            formatSassError(err);
            throw err;
        }
    }
    sass.render(opt, function onRender(err, result) {
        if (err) {
            formatSassError(err);
            callback(err);
            return;
        }

        if (result.map && result.map !== '{}') {
            result.map = JSON.parse(result.map);
            result.map.file = resourcePath;
            // The first source is 'stdin' according to libsass because we've used the data input
            // Now let's override that value with the correct relative path
            result.map.sources[0] = path.relative(self.options.output.path, resourcePath);
        } else {
            result.map = null;
        }

        addIncludedFilesToWebpack(result.stats.includedFiles);
        callback(null, result.css.toString(), result.map);
    });
};

/**
 * Tries to get an excerpt of the file where the error happened.
 * Uses err.line and err.column.
 *
 * Returns an empty string if the excerpt could not be retrieved.
 *
 * @param {SassError} err
 * @returns {string}
 */
function getFileExcerptIfPossible(err) {
    var content;

    try {
        content = fs.readFileSync(err.file, 'utf8');

        return os.EOL +
            content.split(os.EOL)[err.line - 1] + os.EOL +
            new Array(err.column - 1).join(' ') + '^' + os.EOL +
            '      ';
    } catch (err) {
        // If anything goes wrong here, we don't want any errors to be reported to the user
        return '';
    }
}

function getImportsToResolve(originalImport) {
    var ext = path.extname(originalImport);
    var basename = path.basename(originalImport);
    var dirname = path.dirname(originalImport);
    var startsWithUnderscore = basename.charAt(0) === '_';
    var paths = [];

    function add(file) {
        paths.push(dirname + path.sep + file);
    }

    if (originalImport.charAt(0) !== '.') {
        if (dirname === '.') {
            return [originalImport];
        }
    }
    if (ext) {
        if (ext === '.scss' || ext === '.sass') {
            add(basename);
            if (!startsWithUnderscore) {
                add('_' + basename);
            }
        }/* else {
            Leave unknown extensions (like .css) untouched
        }*/
    } else {
        extPrecedence.forEach(function (ext) {
            add('_' + basename + ext);
        });
        extPrecedence.forEach(function (ext) {
            add(basename + ext);
        });
    }

    return paths;
}
<commit_msg>Fix bug with empty files and webpack/enhanced-require<commit_after>'use strict';

var utils = require('loader-utils');
var sass = require('node-sass');
var path = require('path');
var os = require('os');
var fs = require('fs');

// A typical sass error looks like this
var SassError = {
    message: 'invalid property name',
    column: 14,
    line: 1,
    file: 'stdin',
    status: 1
};

var extPrecedence = ['.scss', '.sass', '.css'];
var matchCss = /\.css$/;

/**
 * The sass-loader makes node-sass available to webpack modules.
 *
 * @param {string} content
 * @returns {*}
 */
module.exports = function (content) {
    var callback = this.async();
    var isSync = typeof callback !== 'function';
    var self = this;
    var resourcePath = this.resourcePath;
    var result;
    var opt;

    /**
     * Enhances the sass error with additional information about what actually went wrong.
     *
     * @param {SassError} err
     */
    function formatSassError(err) {
        var msg = err.message;

        if (err.file === 'stdin') {
            err.file = resourcePath;
        }
        // node-sass returns UNIX-style paths
        err.file = path.normalize(err.file);

        // The 'Current dir' hint of node-sass does not help us, we're providing
        // additional information by reading the err.file property
        msg = msg.replace(/\s*Current dir:\s*/, '');

        err.message = getFileExcerptIfPossible(err) +
            msg.charAt(0).toUpperCase() + msg.slice(1) + os.EOL +
            '      in ' + err.file + ' (line ' + err.line + ', column ' + err.column + ')';

        // Instruct webpack to hide the JS stack from the console
        // Usually you're only interested in the SASS stack in this case.
        err.hideStack = true;
    }

    /**
     * Returns an importer that uses webpack's resolving algorithm.
     *
     * It's important that the returned function has the correct number of arguments
     * (based on whether the call is sync or async) because otherwise node-sass doesn't exit.
     *
     * @returns {function}
     */
    function getWebpackImporter() {
        if (isSync) {
            return function syncWebpackImporter(url, context) {
                url = utils.urlToRequest(url, opt.root);
                context = normalizeContext(context);

                return syncResolve(context, url, getImportsToResolve(url));
            };
        }
        return function asyncWebpackImporter(url, context, done) {
            url = utils.urlToRequest(url, opt.root);
            context = normalizeContext(context);

            asyncResolve(context, url, getImportsToResolve(url), done);
        };
    }

    /**
     * Tries to resolve the given url synchronously. If a resolve error occurs, a second try for the same
     * module prefixed with an underscore is started.
     *
     * @param {object} loaderContext
     * @param {string} url
     //* @param {string} context
     * @returns {object}
     */
    function syncResolve(fileContext, originalImport, importsToResolve) {
        var importToResolve = importsToResolve.shift();
        var resolvedFilename;

        if (!importToResolve) {
            return {
                file: originalImport
            };
        }

        try {
            resolvedFilename = self.resolveSync(fileContext, importToResolve);
            resolvedFilename = resolvedFilename.replace(matchCss, '');
            return {
                file: resolvedFilename
            };
        } catch (err) {
            return syncResolve(fileContext, originalImport, importsToResolve);
        }
    }

    /**
     * Tries to resolve the given url asynchronously. If a resolve error occurs, a second try for the same
     * module prefixed with an underscore is started.
     *
     * @param {object} loaderContext
     * @param {string} url
     * @param {string} fileContext
     * @param {function} done
     */
    function asyncResolve(fileContext, originalImport, importsToResolve, done) {
        var importToResolve = importsToResolve.shift();

        if (!importToResolve) {
            done({
                file: originalImport
            });
            return;
        }

        self.resolve(fileContext, importToResolve, function onWebpackResolve(err, resolvedFilename) {
            if (err) {
                asyncResolve(fileContext, originalImport, importsToResolve, done);
                return;
            }
            // Use self.loadModule() before calling done() to make imported files available to
            // other webpack tools like postLoaders etc.?

            resolvedFilename = resolvedFilename.replace(matchCss, '');
            done({
                file: resolvedFilename.replace(matchCss, '')
            });
        });
    }

    function normalizeContext(context) {
        // The first file is 'stdin' when we're using the data option
        if (context === 'stdin') {
            context = resourcePath;
        }
        return path.dirname(context);
    }

    // When files have been imported via the includePaths-option, these files need to be
    // introduced to webpack in order to make them watchable.
    function addIncludedFilesToWebpack(includedFiles) {
        includedFiles.forEach(addNormalizedDependency);
    }

    function addNormalizedDependency(file) {
        // node-sass returns UNIX-style paths
        self.dependency(path.normalize(file));
    }

    this.cacheable();

    opt = utils.parseQuery(this.query);
    opt.data = content;

    // Skip empty files, otherwise it will stop webpack, see issue #21
    if (opt.data.trim() === '') {
        return isSync ? content : callback(null, content);
    }

    // opt.outputStyle
    if (!opt.outputStyle && this.minimize) {
        opt.outputStyle = 'compressed';
    }

    // opt.sourceMap
    // Not using the `this.sourceMap` flag because css source maps are different
    // @see https://github.com/webpack/css-loader/pull/40
    if (opt.sourceMap) {
        // deliberately overriding the sourceMap option
        // this value is (currently) ignored by libsass when using the data input instead of file input
        // however, it is still necessary for correct relative paths in result.map.sources
        opt.sourceMap = this.options.output.path + '/sass.map';
        opt.omitSourceMapUrl = true;

        // If sourceMapContents option is not set, set it to true otherwise maps will be empty/null
        // when exported by webpack-extract-text-plugin.
        if ('sourceMapContents' in opt === false) {
            opt.sourceMapContents = true;
        }
    }

    // indentedSyntax is a boolean flag
    opt.indentedSyntax = Boolean(opt.indentedSyntax);

    opt.importer = getWebpackImporter();

    // start the actual rendering
    if (isSync) {
        try {
            result = sass.renderSync(opt);
            addIncludedFilesToWebpack(result.stats.includedFiles);
            return result.css.toString();
        } catch (err) {
            formatSassError(err);
            throw err;
        }
    }
    sass.render(opt, function onRender(err, result) {
        if (err) {
            formatSassError(err);
            callback(err);
            return;
        }

        if (result.map && result.map !== '{}') {
            result.map = JSON.parse(result.map);
            result.map.file = resourcePath;
            // The first source is 'stdin' according to libsass because we've used the data input
            // Now let's override that value with the correct relative path
            result.map.sources[0] = path.relative(self.options.output.path, resourcePath);
        } else {
            result.map = null;
        }

        addIncludedFilesToWebpack(result.stats.includedFiles);
        callback(null, result.css.toString(), result.map);
    });
};

/**
 * Tries to get an excerpt of the file where the error happened.
 * Uses err.line and err.column.
 *
 * Returns an empty string if the excerpt could not be retrieved.
 *
 * @param {SassError} err
 * @returns {string}
 */
function getFileExcerptIfPossible(err) {
    var content;

    try {
        content = fs.readFileSync(err.file, 'utf8');

        return os.EOL +
            content.split(os.EOL)[err.line - 1] + os.EOL +
            new Array(err.column - 1).join(' ') + '^' + os.EOL +
            '      ';
    } catch (err) {
        // If anything goes wrong here, we don't want any errors to be reported to the user
        return '';
    }
}

function getImportsToResolve(originalImport) {
    var ext = path.extname(originalImport);
    var basename = path.basename(originalImport);
    var dirname = path.dirname(originalImport);
    var startsWithUnderscore = basename.charAt(0) === '_';
    var paths = [];

    function add(file) {
        paths.push(dirname + path.sep + file);
    }

    if (originalImport.charAt(0) !== '.') {
        if (dirname === '.') {
            return [originalImport];
        }
    }
    if (ext) {
        if (ext === '.scss' || ext === '.sass') {
            add(basename);
            if (!startsWithUnderscore) {
                add('_' + basename);
            }
        }/* else {
            Leave unknown extensions (like .css) untouched
        }*/
    } else {
        extPrecedence.forEach(function (ext) {
            add('_' + basename + ext);
        });
        extPrecedence.forEach(function (ext) {
            add(basename + ext);
        });
    }

    return paths;
}
<|endoftext|>


<commit_before>require("babel-register");
require('./src/index');
<commit_msg>Delete index.js<commit_after><|endoftext|>


<commit_before>//-----------------------------------------------------
//
// Author: Daeren Torn
// Site: 666.io
// Version: 0.0.39
//
//-----------------------------------------------------

//-----------------------------------------------------

if(typeof(module) == "object") {
    module.exports = global.$injector = $injector;
}

//-----------------------------------------------------

function $injector(f, binds) {
    if(typeof(f) !== "function") return null;

    var strFunc     = f.toString(),
        strFuncArgs = strFunc.match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m);

    var i, arg,
        funcArgs, argsLen, callStack;

    if(strFuncArgs[1]) {
        strFuncArgs = strFuncArgs[1].replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))|[\s\t\n]+/gm, "");

        if(strFuncArgs) {
            funcArgs = strFuncArgs.split(/,/g);
            argsLen = funcArgs.length;

            if(argsLen)
                callStack = new Array(argsLen);
        }
    }

    return caller;

    function caller(data, ctx) {
        if(!argsLen || !data && !binds)
            return f.apply(ctx|| f);

        i = argsLen;

        while(i--) {
            arg = funcArgs[i];
            callStack[i] = data[arg] || binds && binds[arg];
        }

        return f.apply(ctx || f, callStack);
    }
}
<commit_msg>UP: Ver. fix<commit_after>//-----------------------------------------------------
//
// Author: Daeren Torn
// Site: 666.io
// Version: 0.0.1
//
//-----------------------------------------------------

//-----------------------------------------------------

if(typeof(module) == "object") {
    module.exports = global.$injector = $injector;
}

//-----------------------------------------------------

function $injector(f, binds) {
    if(typeof(f) !== "function") return null;

    var strFunc     = f.toString(),
        strFuncArgs = strFunc.match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m);

    var i, arg,
        funcArgs, argsLen, callStack;

    if(strFuncArgs[1]) {
        strFuncArgs = strFuncArgs[1].replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))|[\s\t\n]+/gm, "");

        if(strFuncArgs) {
            funcArgs = strFuncArgs.split(/,/g);
            argsLen = funcArgs.length;

            if(argsLen)
                callStack = new Array(argsLen);
        }
    }

    return caller;

    function caller(data, ctx) {
        if(!argsLen || !data && !binds)
            return f.apply(ctx|| f);

        i = argsLen;

        while(i--) {
            arg = funcArgs[i];
            callStack[i] = data[arg] || binds && binds[arg];
        }

        return f.apply(ctx || f, callStack);
    }
}
<|endoftext|>


<commit_before>/**
 * An array of words such as "the" and "an", which
 * will never be used as Twitter hashtags.
 */
var stopWords = require('./lib/stopwords');

/**
 * An array of words that could be Twitter hashtags
 * String []
 */
 var words;

/**
 * Takes in a string, removes all filter words, numbers,
 * and other expressions that will not be used in this process.
 *
 * @param  String str, the string to be filtered
 * @return String [] words, the filtered set of words that could be
 * used as Twitter hashtags
 */
function filterText(str) {
	// Make sure that the string is not empty
	if (typeof str != 'string' || str.trim() === '')
		return [];

	// Remove punctuation from input string, and split it into words.
 	words = removePunctuation(str).split(/\s/);
 	// Prune digits and stopwords, return result.
	return pruneWords(words);
}

exports.filterText = filterText;

function pruneWords (words) {
	// Loop through the words to prune digits
	for (var i = 0; i < words.length; i++) {
		// Check if this word is either a digit, or in our list of stopwords
		if (isDigit(words[i]) ||
			stopWords.indexOf(words[i].toLowerCase()) !== -1)
			// Remove the word
			words.splice(i--,1);
	}
	return words;
}

/**
 * Takes in a string, and returns it without any
 * punctuation marks.
 *
 * Expanded on Mike Grace's Stackoverflow response (added '@'):
 * 	http://stackoverflow.com/a/4328722/126320
 * @return String str
 */
function removePunctuation(str) {
	//  Remove  links, periods, commas, semi-colons, etc.
	var punctuationless = str.replace(/[\.,-\/#!$@%\^&\*;:{}=\-_`~()]/g,"");
	return punctuationless.replace(/\s{2,}/g," ");
}

/**
 * Takes in a string, and returns true if it is a digit
 *
 * @param  String str to test
 * @return Boolean isDigit
 */
function isDigit(str) {
	// Find a digit in the string.
	var findDigit = str.match(/\d/g);
	// Return true if the entire string is a number (number are fine within strings.)
    return (findDigit && findDigit.length === str.length);
}<commit_msg>Clean up index.js<commit_after>/**
 * An array of words such as "the" and "an", which
 * will never be used as Twitter hashtags.
 */
var stopWords = require('./lib/stopwords');

/**
 * An array of words that could be Twitter hashtags
 * String []
 */
 var words;

/**
 * Takes in a string, removes all filter words, numbers,
 * and other expressions that will not be used in this process.
 *
 * @param  String str, the string to be filtered
 * @return String [] words, the filtered set of words that could be
 * used as Twitter hashtags
 */
function filterText(str) {
	// Make sure that the string is not empty
	if (typeof str != 'string' || str.trim() === '')
		return [];

	// Remove punctuation from input string, and split it into words.
 	words = removePunctuation(str).split(/\s/);
 	// Prune digits and stopwords, return result.
	return pruneWords(words);
}

function pruneWords (words) {
	// Loop through the words to prune digits
	for (var i = 0; i < words.length; i++) {
		// Check if this word is either a digit, or in our list of stopwords
		if (isDigit(words[i]) ||
			stopWords.indexOf(words[i].toLowerCase()) !== -1)
			// Remove the word
			words.splice(i--,1);
	}
	return words;
}

/**
 * Takes in a string, and returns it without any
 * punctuation marks.
 *
 * Expanded on Mike Grace's Stackoverflow response (added '@'):
 * 	http://stackoverflow.com/a/4328722/126320
 * @return String str
 */
function removePunctuation(str) {
	//  Remove  links, periods, commas, semi-colons, etc.
	var punctuationless = str.replace(/[\.,-\/#!$@%\^&\*;:{}=\-_`~()]/g,"");
	return punctuationless.replace(/\s{2,}/g," ");
}

/**
 * Takes in a string, and returns true if it is a digit
 *
 * @param  String str to test
 * @return Boolean isDigit
 */
function isDigit(str) {
	// Find a digit in the string.
	var findDigit = str.match(/\d/g);
	// Return true if the entire string is a number (number are fine within strings.)
    return (findDigit && findDigit.length === str.length);
}

// For testing:
exports.filterText = filterText;<|endoftext|>


<commit_before>import { Formatter } from './formatter';
import t from 'should-type';

import { addSpaces, pad0, functionName, constructorName } from './util';

import { formatPlainObject, formatPlainObjectKey } from './format/object';
import { formatWrapper1, formatWrapper2 } from './format/primitive-type-wrappers';
import { formatRegExp } from './format/regexp';

import { formatFunction } from './format/function';

import { formatArray } from './format/array';
import { formatArguments } from './format/arguments';
import { formatDate } from './format/date';
import { formatError } from './format/error';

import { generateFormatForNumberArray } from './format/number-array';

import { formatMap } from './format/map';
import { formatSet } from './format/set';

import { genSimdVectorFormat } from './format/simd';

function defaultFormat(value, opts) {
  return new Formatter(opts).format(value);
}

defaultFormat.Formatter = Formatter;
defaultFormat.addSpaces = addSpaces;
defaultFormat.pad0 = pad0;
defaultFormat.functionName = functionName;
defaultFormat.constructorName = constructorName;
defaultFormat.formatPlainObjectKey = formatPlainObjectKey;
export default defaultFormat;

// adding primitive types
Formatter.addType(new t.Type(t.UNDEFINED), function() {
  return 'undefined';
});
Formatter.addType(new t.Type(t.NULL), function() {
  return 'null';
});
Formatter.addType(new t.Type(t.BOOLEAN), function(value) {
  return value ? 'true': 'false';
});
Formatter.addType(new t.Type(t.SYMBOL), function(value) {
  return value.toString();
});
Formatter.addType(new t.Type(t.NUMBER), function(value) {
  if (value === 0 && 1 / value < 0) {
    return '-0';
  }
  return String(value);
});

Formatter.addType(new t.Type(t.STRING), function(value) {
  return '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
      .replace(/'/g, "\\'")
      .replace(/\\"/g, '"') + '\'';
});

Formatter.addType(new t.Type(t.FUNCTION), formatFunction);

// plain object
Formatter.addType(new t.Type(t.OBJECT), formatPlainObject);

// type wrappers
Formatter.addType(new t.Type(t.OBJECT, t.NUMBER), formatWrapper1);
Formatter.addType(new t.Type(t.OBJECT, t.BOOLEAN), formatWrapper1);
Formatter.addType(new t.Type(t.OBJECT, t.STRING), formatWrapper2);

Formatter.addType(new t.Type(t.OBJECT, t.REGEXP), formatRegExp);
Formatter.addType(new t.Type(t.OBJECT, t.ARRAY), formatArray);
Formatter.addType(new t.Type(t.OBJECT, t.ARGUMENTS), formatArguments);
Formatter.addType(new t.Type(t.OBJECT, t.DATE), formatDate);
Formatter.addType(new t.Type(t.OBJECT, t.ERROR), formatError);
Formatter.addType(new t.Type(t.OBJECT, t.SET), formatSet);
Formatter.addType(new t.Type(t.OBJECT, t.MAP), formatMap);
Formatter.addType(new t.Type(t.OBJECT, t.WEAK_MAP), formatMap);
Formatter.addType(new t.Type(t.OBJECT, t.WEAK_SET), formatSet);

Formatter.addType(new t.Type(t.OBJECT, t.BUFFER), generateFormatForNumberArray('length', 'Buffer', 2));

Formatter.addType(new t.Type(t.OBJECT, t.ARRAY_BUFFER), generateFormatForNumberArray('byteLength', 'ArrayBuffer', 2));

Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'int8'), generateFormatForNumberArray('length', 'Int8Array', 2));
Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'uint8'), generateFormatForNumberArray('length', 'Uint8Array', 2));
Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'uint8clamped'), generateFormatForNumberArray('length', 'Uint8ClampedArray', 2));

Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'int16'), generateFormatForNumberArray('length', 'Int16Array', 4));
Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'uint16'), generateFormatForNumberArray('length', 'Uint16Array', 4));

Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'int32'), generateFormatForNumberArray('length', 'Int32Array', 8));
Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'uint32'), generateFormatForNumberArray('length', 'Uint32Array', 8));

Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'bool16x8'), genSimdVectorFormat('Bool16x8', 8));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'bool32x4'), genSimdVectorFormat('Bool32x4', 4));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'bool8x16'), genSimdVectorFormat('Bool8x16', 16));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'float32x4'), genSimdVectorFormat('Float32x4', 4));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'int16x8'), genSimdVectorFormat('Int16x8', 8));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'int32x4'), genSimdVectorFormat('Int32x4', 4));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'int8x16'), genSimdVectorFormat('Int8x16', 16));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'uint16x8'), genSimdVectorFormat('Uint16x8', 8));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'uint32x4'), genSimdVectorFormat('Uint32x4', 4));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'uint8x16'), genSimdVectorFormat('Uint8x16', 16));

Formatter.addType(new t.Type(t.OBJECT, t.PROMISE), function() {
  return '[Promise]';//TODO it could be nice to inspect its state and value
});

Formatter.addType(new t.Type(t.OBJECT, t.XHR), function() {
  return '[XMLHttpRequest]';//TODO it could be nice to inspect its state
});

Formatter.addType(new t.Type(t.OBJECT, t.HTML_ELEMENT), function(value) {
  return value.outerHTML;
});

Formatter.addType(new t.Type(t.OBJECT, t.HTML_ELEMENT, '#text'), function(value) {
  return value.nodeValue;
});

Formatter.addType(new t.Type(t.OBJECT, t.HTML_ELEMENT, '#document'), function(value) {
  return value.documentElement.outerHTML;
});

Formatter.addType(new t.Type(t.OBJECT, t.HOST), function() {
  return '[Host]';
});
<commit_msg>Export forEach format<commit_after>import { Formatter } from './formatter';
import t from 'should-type';

import { addSpaces, pad0, functionName, constructorName } from './util';

import { typeAdaptorForEachFormat } from './format/type-adaptor-for-each';
import { formatPlainObject, formatPlainObjectKey } from './format/object';
import { formatWrapper1, formatWrapper2 } from './format/primitive-type-wrappers';
import { formatRegExp } from './format/regexp';

import { formatFunction } from './format/function';

import { formatArray } from './format/array';
import { formatArguments } from './format/arguments';
import { formatDate } from './format/date';
import { formatError } from './format/error';

import { generateFormatForNumberArray } from './format/number-array';

import { formatMap } from './format/map';
import { formatSet } from './format/set';

import { genSimdVectorFormat } from './format/simd';

function defaultFormat(value, opts) {
  return new Formatter(opts).format(value);
}

defaultFormat.Formatter = Formatter;
defaultFormat.addSpaces = addSpaces;
defaultFormat.pad0 = pad0;
defaultFormat.functionName = functionName;
defaultFormat.constructorName = constructorName;
defaultFormat.formatPlainObjectKey = formatPlainObjectKey;
defaultFormat.typeAdaptorForEachFormat = typeAdaptorForEachFormat;
export default defaultFormat;

// adding primitive types
Formatter.addType(new t.Type(t.UNDEFINED), function() {
  return 'undefined';
});
Formatter.addType(new t.Type(t.NULL), function() {
  return 'null';
});
Formatter.addType(new t.Type(t.BOOLEAN), function(value) {
  return value ? 'true': 'false';
});
Formatter.addType(new t.Type(t.SYMBOL), function(value) {
  return value.toString();
});
Formatter.addType(new t.Type(t.NUMBER), function(value) {
  if (value === 0 && 1 / value < 0) {
    return '-0';
  }
  return String(value);
});

Formatter.addType(new t.Type(t.STRING), function(value) {
  return '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
      .replace(/'/g, "\\'")
      .replace(/\\"/g, '"') + '\'';
});

Formatter.addType(new t.Type(t.FUNCTION), formatFunction);

// plain object
Formatter.addType(new t.Type(t.OBJECT), formatPlainObject);

// type wrappers
Formatter.addType(new t.Type(t.OBJECT, t.NUMBER), formatWrapper1);
Formatter.addType(new t.Type(t.OBJECT, t.BOOLEAN), formatWrapper1);
Formatter.addType(new t.Type(t.OBJECT, t.STRING), formatWrapper2);

Formatter.addType(new t.Type(t.OBJECT, t.REGEXP), formatRegExp);
Formatter.addType(new t.Type(t.OBJECT, t.ARRAY), formatArray);
Formatter.addType(new t.Type(t.OBJECT, t.ARGUMENTS), formatArguments);
Formatter.addType(new t.Type(t.OBJECT, t.DATE), formatDate);
Formatter.addType(new t.Type(t.OBJECT, t.ERROR), formatError);
Formatter.addType(new t.Type(t.OBJECT, t.SET), formatSet);
Formatter.addType(new t.Type(t.OBJECT, t.MAP), formatMap);
Formatter.addType(new t.Type(t.OBJECT, t.WEAK_MAP), formatMap);
Formatter.addType(new t.Type(t.OBJECT, t.WEAK_SET), formatSet);

Formatter.addType(new t.Type(t.OBJECT, t.BUFFER), generateFormatForNumberArray('length', 'Buffer', 2));

Formatter.addType(new t.Type(t.OBJECT, t.ARRAY_BUFFER), generateFormatForNumberArray('byteLength', 'ArrayBuffer', 2));

Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'int8'), generateFormatForNumberArray('length', 'Int8Array', 2));
Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'uint8'), generateFormatForNumberArray('length', 'Uint8Array', 2));
Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'uint8clamped'), generateFormatForNumberArray('length', 'Uint8ClampedArray', 2));

Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'int16'), generateFormatForNumberArray('length', 'Int16Array', 4));
Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'uint16'), generateFormatForNumberArray('length', 'Uint16Array', 4));

Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'int32'), generateFormatForNumberArray('length', 'Int32Array', 8));
Formatter.addType(new t.Type(t.OBJECT, t.TYPED_ARRAY, 'uint32'), generateFormatForNumberArray('length', 'Uint32Array', 8));

Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'bool16x8'), genSimdVectorFormat('Bool16x8', 8));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'bool32x4'), genSimdVectorFormat('Bool32x4', 4));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'bool8x16'), genSimdVectorFormat('Bool8x16', 16));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'float32x4'), genSimdVectorFormat('Float32x4', 4));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'int16x8'), genSimdVectorFormat('Int16x8', 8));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'int32x4'), genSimdVectorFormat('Int32x4', 4));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'int8x16'), genSimdVectorFormat('Int8x16', 16));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'uint16x8'), genSimdVectorFormat('Uint16x8', 8));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'uint32x4'), genSimdVectorFormat('Uint32x4', 4));
Formatter.addType(new t.Type(t.OBJECT, t.SIMD, 'uint8x16'), genSimdVectorFormat('Uint8x16', 16));

Formatter.addType(new t.Type(t.OBJECT, t.PROMISE), function() {
  return '[Promise]';//TODO it could be nice to inspect its state and value
});

Formatter.addType(new t.Type(t.OBJECT, t.XHR), function() {
  return '[XMLHttpRequest]';//TODO it could be nice to inspect its state
});

Formatter.addType(new t.Type(t.OBJECT, t.HTML_ELEMENT), function(value) {
  return value.outerHTML;
});

Formatter.addType(new t.Type(t.OBJECT, t.HTML_ELEMENT, '#text'), function(value) {
  return value.nodeValue;
});

Formatter.addType(new t.Type(t.OBJECT, t.HTML_ELEMENT, '#document'), function(value) {
  return value.documentElement.outerHTML;
});

Formatter.addType(new t.Type(t.OBJECT, t.HOST), function() {
  return '[Host]';
});
<|endoftext|>


<commit_before>var RETHINKDB_DATATABLE = function() {
  var helper = require('./helper');

  /**
   * Build a rethinkdb query to extract data to be used by datatables
   * @function buildDataTablesQuery
   * @param {!object} params parsed parameters from datatables (check https://datatables.net/manual/server-side for more info)
   * @param {!object} rethinkdb your rethinkdb driver
   * @param {!object} tableSelectionQuery the table selection query (ie: r.db('example').table('test'))
   * @param {?object} options optional variables to ensure the functionality & security of our data
   * @param {string[]} options.searchable array containing names of searchable fields in the table
   * @param {string[]} options.pluckable array containing names of pluckable fields (i.e. 'password' should not be pluckable)
   * @param {string} options.primaryKey the primary key name of the table (defaults to 'id')
   * @param {!function} cb the callback function
   * @returns {object} the query to be run
   */
  this.buildDataTablesQuery = function (params, rethinkdb, tableSelectionQuery, options, cb) {
    if (typeof options === 'function') {
      cb = options;
      options = {};
    }
    var searchable = ('searchable' in options) ? options['searchable'] : null;
    var pluckable = ('pluckable' in options) ? options['pluckable'] : null;
    var primaryKey = ('primaryKey' in options) ? options['primaryKey'] : 'id';
    var query = tableSelectionQuery;

    validateDataTableParams(params, function(err, validated) {
      if (err) return cb(err);

      if (!searchable) {
        //Build searchable based on parameters from datatables request
        seachable = [];
        validated['columns'].forEach(function (column) {
          if (column['searchable'])
            searchable.push(column['data']);
        });
      }

      //We want to return an empty string in case an object does not have required field
      var defaultRow = {};

      //Build pluckable and defaultRow based on parameters from datatables request
      if (!pluckable) {
        pluckable = [];
        validated['columns'].forEach(function (column) {
          pluckable.push(column['data']);
        });
      } else {
        var furtherPlucking = [];
        validated['columns'].forEach(function (column) {
          if (pluckable.indexOf(column['data']) > -1) {
            furtherPlucking.push(column['data']);
            defaultRow[column['data']] = '';
          }
        });
        pluckable = furtherPlucking;
      }

      pluckable.push('DT_RowId');

      if (validated['search'] && validated['search']['value']!=="") {
        if (validated['search']['regex'] && (validated['search']['regex'] === 'true' || validated['search']['regex'] == true)) {
          query = query.filter(function(record) {
            return rethinkdb.expr(searchable).map(function(key) {
              return record(key).default('').coerceTo('string').match(validated['search']['value']).ne(null)
            }).contains(true)
          });
        } else {
          query = query.filter(function(record) {
            return rethinkdb.expr(searchable).map(function(key) {
              return record(key).default('').coerceTo('string').eq(validated['search']['value'])
            }).contains(true)
          });
        }
      }

      var orderColumn = validated['columns'][parseInt(params['order'][0]['column'])]['name'];
      var order = (validated['order'][0]['dir'] === 'desc') ? rethinkdb.desc(orderColumn) : orderColumn;

      query = query.coerceTo('array').do(function(records) {
        return {
          draw: validated['draw'],
          recordsTotal: tableSelectionQuery.count(),
          recordsFiltered: records.count(),
          data: records.orderBy(order).slice(validated['start'], validated['start'] + validated['length']).merge(function(row) {
            return {
              DT_RowId : row(primaryKey)
            }
          }).map(function(row) {
            return rethinkdb.expr(defaultRow).merge(row);
          })
          .pluck(rethinkdb.args(pluckable))
        }
      });

      return cb(null, query);
    });
  };

  /**
   * Validate dataTable parameters
   * Currently not supporting search on each column
   * @function validateDataTableParams
   * @param {integer} draw draw counter for datatables to keep track
   * @param {integer} start first record index
   * @param {integer} length number of records in the current draw (-1 for everything)
   * @param {object} search object with value(string) & regex(boolean) properties
   * indicating search on searchable columns
   * @param {object[]} order array of {column: <col_index>, dir: <asc or desc string>}
   * indicating which ordering should be applied
   * @param {object[]} columns array of objects
   * {
   *  data: <Column's data source string>,
   *  name: <Column's name string>,
   *  searchable: <boolean to indicate if this column is searchable>,
   *  orderable: <boolean indicate if this column is orderable>,
   *  search {
   *    value: <value to apply to this specific colum>,
   *    regex: <indicate if the search term for this column should be treated as regular expression>
   *  }
   * }
   * @returns {object} validated params
   */
  function validateDataTableParams (params, cb) {
    try {
      var validated = {
        draw: helper.validInt(params ,'draw'),
        start: helper.validInt(params, 'start'),
        length: helper.validInt(params, 'length'),
        search: null,
        order: [],
        columns: []
      };

      if(params['search']) {
        validated['search'] = {};
        validated['search']['regex'] = helper.validBoolean(params['search'], 'regex');
        if (validated['search']['regex']) {
          validated['search']['value'] = helper.regexEscape(params['search']['value']);
        } else {
          validated['search']['value'] = params['search']['value'];
        }
      }

      if (!Array.isArray(params['order']) || params['order'].length === 0) {
        return cb(new Error('Parameter order must be valid array'));
      }

      params['order'].forEach(function(order) {
        var validDir = ['asc', 'desc'];
        order['column'] = helper.validInt(order, 'column');
        order['dir'] = helper.noEmpty(order, 'dir');
        if (validDir.indexOf(order['dir']) < 0) {
          return cb(new Error('Parameter order direction must be asc or desc'));
        }
        validated['order'].push(order);
      });

      if (!Array.isArray(params['columns']) || params['columns'].length === 0) {
        return cb(new Error('Parameter column must be valid array'));
      }

      params['columns'].forEach(function(column) {
        column['data'] = helper.noEmpty(column, 'data');
        column['name'] = helper.noEmpty(column, 'name');
        (column['searchable']) ? column['searchable'] = helper.validBoolean(column, 'searchable') : null;
        (column['orderable']) ? column['orderable'] = helper.validBoolean(column, 'orderable') : null;
          validated['columns'].push(column);
      });

      return cb(null, validated);
    } catch (error) {
      return cb(error);
    }
  }
}

var rethinkdb_datable = new RETHINKDB_DATATABLE();
module.exports = rethinkdb_datable;<commit_msg>Added regexCaseSensitive option; Minor refactor;<commit_after>var RETHINKDB_DATATABLE = function() {
  var helper = require('./helper');

  /**
   * Build a rethinkdb query to extract data to be used by datatables
   * @function buildDataTablesQuery
   * @param {!object} params parsed parameters from datatables (check https://datatables.net/manual/server-side for more info)
   * @param {!object} rethinkdb your rethinkdb driver
   * @param {!object} tableSelectionQuery the table selection query (ie: r.db('example').table('test'))
   * @param {?object} options optional variables to ensure the functionality & security of our data
   * @param {string[]} options.searchable array containing names of searchable fields in the table
   * @param {string[]} options.pluckable array containing names of pluckable fields (i.e. 'password' should not be pluckable)
   * @param {string} options.primaryKey the primary key name of the table (defaults to 'id')
   * @param {!function} cb the callback function
   * @returns {object} the query to be run
   */
  this.buildDataTablesQuery = function (params, rethinkdb, tableSelectionQuery, options, cb) {
    if (typeof options === 'function') {
      cb = options;
      options = {};
    }
    var searchable = ('searchable' in options) ? options['searchable'] : null;
    var pluckable = ('pluckable' in options) ? options['pluckable'] : null;
    var primaryKey = ('primaryKey' in options) ? options['primaryKey'] : 'id';
    var regexCaseSensitive = ('primaryKey' in options) ? validBoolean(options['regexCaseSensitive']) : false;
    var query = tableSelectionQuery;

    validateDataTableParams(params, function(err, validated) {
      if (err) return cb(err);

      if (!searchable) {
        //Build searchable based on parameters from datatables request
        seachable = [];
        validated['columns'].forEach(function (column) {
          if (column['searchable'])
            searchable.push(column['data']);
        });
      }

      //We want to return an empty string in case an object does not have required field
      var defaultRow = {};

      //Build pluckable and defaultRow based on parameters from datatables request
      if (!pluckable) {
        pluckable = [];
        validated['columns'].forEach(function (column) {
          pluckable.push(column['data']);
        });
      } else {
        var furtherPlucking = [];
        validated['columns'].forEach(function (column) {
          if (pluckable.indexOf(column['data']) > -1) {
            furtherPlucking.push(column['data']);
            defaultRow[column['data']] = '';
          }
        });
        pluckable = furtherPlucking;
      }

      pluckable.push('DT_RowId');

      if (validated['search'] && validated['search']['value']!=="") {
        if (validated['search']['regex']) {
          var regex = (regexCaseSensitive) ? validated['search']['value'] : '(?i)' + validated['search']['value'];
          query = query.filter(function(record) {
            return rethinkdb.expr(searchable).map(function(key) {
              return record(key).default('').coerceTo('string').match(validated['search']['value']).ne(null)
            }).contains(true)
          });
        } else {
          query = query.filter(function(record) {
            return rethinkdb.expr(searchable).map(function(key) {
              return record(key).default('').coerceTo('string').eq(validated['search']['value'])
            }).contains(true)
          });
        }
      }

      var orderColumn = validated['columns'][parseInt(params['order'][0]['column'])]['name'];
      var order = (validated['order'][0]['dir'] === 'desc') ? rethinkdb.desc(orderColumn) : orderColumn;

      query = query.coerceTo('array').do(function(records) {
        return {
          draw: validated['draw'],
          recordsTotal: tableSelectionQuery.count(),
          recordsFiltered: records.count(),
          data: records.orderBy(order).slice(validated['start'], validated['start'] + validated['length']).merge(function(row) {
            return {
              DT_RowId : row(primaryKey)
            }
          }).map(function(row) {
            return rethinkdb.expr(defaultRow).merge(row);
          })
          .pluck(rethinkdb.args(pluckable))
        }
      });

      return cb(null, query);
    });
  };

  /**
   * Validate dataTable parameters
   * Currently not supporting search on each column
   * @function validateDataTableParams
   * @param {integer} draw draw counter for datatables to keep track
   * @param {integer} start first record index
   * @param {integer} length number of records in the current draw (-1 for everything)
   * @param {object} search object with value(string) & regex(boolean) properties
   * indicating search on searchable columns
   * @param {object[]} order array of {column: <col_index>, dir: <asc or desc string>}
   * indicating which ordering should be applied
   * @param {object[]} columns array of objects
   * {
   *  data: <Column's data source string>,
   *  name: <Column's name string>,
   *  searchable: <boolean to indicate if this column is searchable>,
   *  orderable: <boolean indicate if this column is orderable>,
   *  search {
   *    value: <value to apply to this specific colum>,
   *    regex: <indicate if the search term for this column should be treated as regular expression>
   *  }
   * }
   * @returns {object} validated params
   */
  function validateDataTableParams (params, cb) {
    try {
      var validated = {
        draw: helper.validInt(params ,'draw'),
        start: helper.validInt(params, 'start'),
        length: helper.validInt(params, 'length'),
        search: null,
        order: [],
        columns: []
      };

      if(params['search']) {
        validated['search'] = {};
        validated['search']['regex'] = helper.validBoolean(params['search'], 'regex');
        if (validated['search']['regex']) {
          validated['search']['value'] = helper.regexEscape(params['search']['value']);
        } else {
          validated['search']['value'] = params['search']['value'];
        }
      }

      if (!Array.isArray(params['order']) || params['order'].length === 0) {
        return cb(new Error('Parameter order must be valid array'));
      }

      params['order'].forEach(function(order) {
        var validDir = ['asc', 'desc'];
        order['column'] = helper.validInt(order, 'column');
        order['dir'] = helper.noEmpty(order, 'dir');
        if (validDir.indexOf(order['dir']) < 0) {
          return cb(new Error('Parameter order direction must be asc or desc'));
        }
        validated['order'].push(order);
      });

      if (!Array.isArray(params['columns']) || params['columns'].length === 0) {
        return cb(new Error('Parameter column must be valid array'));
      }

      params['columns'].forEach(function(column) {
        column['data'] = helper.noEmpty(column, 'data');
        column['name'] = helper.noEmpty(column, 'name');
        (column['searchable']) ? column['searchable'] = helper.validBoolean(column, 'searchable') : null;
        (column['orderable']) ? column['orderable'] = helper.validBoolean(column, 'orderable') : null;
          validated['columns'].push(column);
      });

      return cb(null, validated);
    } catch (error) {
      return cb(error);
    }
  }
}

var rethinkdb_datable = new RETHINKDB_DATATABLE();
module.exports = rethinkdb_datable;<|endoftext|>


<commit_before>var fs = require("fs");
var tmp = require("tmp");
var path = require("path");
var compile = require("node-elm-compiler").compile;
var jsEmitterFilename = "emitter.js";

var KNOWN_MODULES =
  [
    "Native",
    "fullscreen",
    "embed",
    "worker",
    "Basics",
    "Maybe",
    "List",
    "Array",
    "Char",
    "Color",
    "Transform2D",
    "Text",
    "Graphics",
    "Debug",
    "Result",
    "Task",
    "Signal",
    "String",
    "Dict",
    "Json",
    "Regex",
    "VirtualDom",
    "Html",
    "Css"
  ];

// elmModuleName is optional, and is by default inferred based on the filename.
module.exports = function(projectDir, stylesheetsPath, outputDir, stylesheetsModule, stylesheetsPort) {

  var originalWorkingDir = process.cwd();
  process.chdir(projectDir);

  return createTmpDir()
    .then(function (tmpDirPath) {
      return generateCssFiles(
        stylesheetsPath,
        path.join(tmpDirPath, jsEmitterFilename),
        outputDir,
        stylesheetsModule || "Stylesheets",
        stylesheetsPort || "files"
      );
    })
    .then(function(result) {
      process.chdir(originalWorkingDir);
      return result;
    })
    .catch(function(err) {
      process.chdir(originalWorkingDir);
      throw Error(err);
    });
}

function createTmpDir() {
  return new Promise(function (resolve, reject) {
    tmp.dir(function (err, tmpDirPath) {
      if (err) {
        reject(err);
      } else {
        resolve(tmpDirPath);
      }
    });
  });
}

function generateCssFiles(stylesheetsPath, emitterDest, outputDir, stylesheetsModule, stylesheetsPort) {
  return emit(stylesheetsPath, emitterDest, stylesheetsModule, stylesheetsPort)
    .then(writeResults(outputDir));
}

function emit(src, dest, stylesheetsModule, stylesheetsPort) {
    // Compile the temporary file.
  return compileEmitter(src, {output: dest, yes: true})
    .then(makeRequirable(dest))
    .then(extractCssResults(dest, stylesheetsModule, stylesheetsPort));
}

function suggestModulesNames(Elm){
  return Object.keys(Elm).filter(function(key){
    return KNOWN_MODULES.indexOf(key) === -1;
  })
}

function missingEntryModuleMessage(stylesheetsModule, Elm){
  var errorMessage = "I couldn't find the entry module " + stylesheetsModule + ".\n";
  var suggestions = suggestModulesNames(Elm);

  if (suggestions.length > 1){
    errorMessage += "\nMaybe you meant one of these: " + suggestions.join(",");
  } else if (suggestions.length === 1){
    errorMessage += "\nMaybe you meant: " + suggestions;
  }

  errorMessage += "\nYou can pass me a different module to use with --module=<moduleName>";

  return errorMessage;
}

function noPortsMessage(stylesheetsModule, stylesheetsPort){
  var errorMessage = "The module " + stylesheetsModule + " doesn't expose any ports!\n";

  errorMessage += "\nI was looking for a port called `" + stylesheetsPort + "` but couldn't find it!";
  errorMessage += "\n\nTry adding something like";
  errorMessage += `
port ${stylesheetsPort} : CssFileStructure
port ${stylesheetsPort} =
  toFileStructure
    []

to ${stylesheetsModule}!
`;

  return errorMessage.trim();
}

function noMatchingPortMessage(stylesheetsModule, stylesheetsPort, ports){
  var errorMessage = `The module ${stylesheetsModule} has no port called ${stylesheetsPort}.\n`;
  errorMessage += "\nI was looking for a port called `" + stylesheetsPort + "` but couldn't find it!";

  var portKeys = Object.keys(ports);

  if (portKeys.length === 1){
    errorMessage += "\nHowever, I did find the port: " + portKeys[0];
    errorMessage += "\nMaybe you meant that instead?";
  } else {
    errorMessage += "\nHowever, I did find the ports : " + Object.keys(ports).join(",");
  }

  errorMessage += "\n\nYou can specify which port to use by doing";
  errorMessage += "\nelm-css -p <port-name>";

  return errorMessage.trim();
}

/*
This is a poor man's type error. To get better error messages, might be worth
considered moving to how elm-static-site does it instead, and use Elm's compiler
for type errors!
*/
function portTypeErrorMessage(stylesheetsModule, stylesheetsPort){
  var errorMessage = `
The type of the port ${stylesheetsPort} was not what I wanted!
I was expecting a list but got ${typeof stylesheetsPort}!
`;

  return errorMessage.trim();
}

function extractCssResults(dest, stylesheetsModule, stylesheetsPort) {
  return function () {
    return new Promise(function (resolve, reject) {
      var Elm = require(dest);

      if (!(stylesheetsModule in Elm)){
        return reject(missingEntryModuleMessage(stylesheetsModule, Elm));
      }

      var worker = Elm.worker(Elm[stylesheetsModule]);

      if (Object.keys(worker.ports).length === 0){
        return reject(noPortsMessage(stylesheetsModule, stylesheetsPort));
      }

      if (!(stylesheetsPort in worker.ports)){
        return reject(noMatchingPortMessage(stylesheetsModule, stylesheetsPort, worker.ports));
      }

      var stylesheets = worker.ports[stylesheetsPort];

      if (!Array.isArray(stylesheets)){
        return reject(portTypeErrorMessage(stylesheetsModule, stylesheetsPort));
      }

      var failures = stylesheets.filter(function(result) {
        return !result.success;
      });

      return failures.length > 0
      ? reject(reportFailures(failures))
      : resolve(stylesheets);
    });
  };
}

function makeRequirable(dest) {
  return function () {
    return new Promise(function (resolve, reject) {
      // Make the compiled emitter.js Node-friendly.
      fs.appendFile(dest, "\nmodule.exports = Elm;", function(err) {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  }
}

function writeResults(outputDir) {
  return function(results) {
    return Promise.all(
      results.map(writeResult(outputDir))
    );
  };
}

function writeResult(outputDir) {
  return function (result) {
    return new Promise(function(resolve, reject) {
      fs.writeFile(path.join(outputDir, result.filename), result.content + "\n", function(err, file) {
        return err ? reject(err) : resolve(result);
      });
    });
  }
}

function reportFailures(failures) {
  return "The following errors occurred during compilation:\n\n" +
    failures.map(function(result) {
      return result.filename + ": " + result.content;
    }).join("\n\n");
}

function compileEmitter(src, options) {
  return new Promise(function(resolve, reject) {
    compile(src, options)
      .on("close", function(exitCode) {
        if (exitCode === 0) {
          resolve();
        } else {
          reject("Errored with exit code " + exitCode);
        }
      });
  });
}
<commit_msg>fix type checking message<commit_after>var fs = require("fs");
var tmp = require("tmp");
var path = require("path");
var compile = require("node-elm-compiler").compile;
var jsEmitterFilename = "emitter.js";

var KNOWN_MODULES =
  [
    "Native",
    "fullscreen",
    "embed",
    "worker",
    "Basics",
    "Maybe",
    "List",
    "Array",
    "Char",
    "Color",
    "Transform2D",
    "Text",
    "Graphics",
    "Debug",
    "Result",
    "Task",
    "Signal",
    "String",
    "Dict",
    "Json",
    "Regex",
    "VirtualDom",
    "Html",
    "Css"
  ];

// elmModuleName is optional, and is by default inferred based on the filename.
module.exports = function(projectDir, stylesheetsPath, outputDir, stylesheetsModule, stylesheetsPort) {

  var originalWorkingDir = process.cwd();
  process.chdir(projectDir);

  return createTmpDir()
    .then(function (tmpDirPath) {
      return generateCssFiles(
        stylesheetsPath,
        path.join(tmpDirPath, jsEmitterFilename),
        outputDir,
        stylesheetsModule || "Stylesheets",
        stylesheetsPort || "files"
      );
    })
    .then(function(result) {
      process.chdir(originalWorkingDir);
      return result;
    })
    .catch(function(err) {
      process.chdir(originalWorkingDir);
      throw Error(err);
    });
}

function createTmpDir() {
  return new Promise(function (resolve, reject) {
    tmp.dir(function (err, tmpDirPath) {
      if (err) {
        reject(err);
      } else {
        resolve(tmpDirPath);
      }
    });
  });
}

function generateCssFiles(stylesheetsPath, emitterDest, outputDir, stylesheetsModule, stylesheetsPort) {
  return emit(stylesheetsPath, emitterDest, stylesheetsModule, stylesheetsPort)
    .then(writeResults(outputDir));
}

function emit(src, dest, stylesheetsModule, stylesheetsPort) {
    // Compile the temporary file.
  return compileEmitter(src, {output: dest, yes: true})
    .then(makeRequirable(dest))
    .then(extractCssResults(dest, stylesheetsModule, stylesheetsPort));
}

function suggestModulesNames(Elm){
  return Object.keys(Elm).filter(function(key){
    return KNOWN_MODULES.indexOf(key) === -1;
  })
}

function missingEntryModuleMessage(stylesheetsModule, Elm){
  var errorMessage = "I couldn't find the entry module " + stylesheetsModule + ".\n";
  var suggestions = suggestModulesNames(Elm);

  if (suggestions.length > 1){
    errorMessage += "\nMaybe you meant one of these: " + suggestions.join(",");
  } else if (suggestions.length === 1){
    errorMessage += "\nMaybe you meant: " + suggestions;
  }

  errorMessage += "\nYou can pass me a different module to use with --module=<moduleName>";

  return errorMessage;
}

function noPortsMessage(stylesheetsModule, stylesheetsPort){
  var errorMessage = "The module " + stylesheetsModule + " doesn't expose any ports!\n";

  errorMessage += "\nI was looking for a port called `" + stylesheetsPort + "` but couldn't find it!";
  errorMessage += "\n\nTry adding something like";
  errorMessage += `
port ${stylesheetsPort} : CssFileStructure
port ${stylesheetsPort} =
  toFileStructure
    []

to ${stylesheetsModule}!
`;

  return errorMessage.trim();
}

function noMatchingPortMessage(stylesheetsModule, stylesheetsPort, ports){
  var errorMessage = `The module ${stylesheetsModule} has no port called ${stylesheetsPort}.\n`;
  errorMessage += "\nI was looking for a port called `" + stylesheetsPort + "` but couldn't find it!";

  var portKeys = Object.keys(ports);

  if (portKeys.length === 1){
    errorMessage += "\nHowever, I did find the port: " + portKeys[0];
    errorMessage += "\nMaybe you meant that instead?";
  } else {
    errorMessage += "\nHowever, I did find the ports : " + Object.keys(ports).join(",");
  }

  errorMessage += "\n\nYou can specify which port to use by doing";
  errorMessage += "\nelm-css -p <port-name>";

  return errorMessage.trim();
}

/*
This is a poor man's type error. To get better error messages, might be worth
considered moving to how elm-static-site does it instead, and use Elm's compiler
for type errors!
*/
function portTypeErrorMessage(stylesheetsModule, stylesheetsPort, portValue){
  var errorMessage = `
The type of the port ${stylesheetsPort} was not what I wanted!
I was expecting a List CssFileStructure but got ${typeof portValue}!
`;

  return errorMessage.trim();
}

function extractCssResults(dest, stylesheetsModule, stylesheetsPort) {
  return function () {
    return new Promise(function (resolve, reject) {
      var Elm = require(dest);

      if (!(stylesheetsModule in Elm)){
        return reject(missingEntryModuleMessage(stylesheetsModule, Elm));
      }

      var worker = Elm.worker(Elm[stylesheetsModule]);

      if (Object.keys(worker.ports).length === 0){
        return reject(noPortsMessage(stylesheetsModule, stylesheetsPort));
      }

      if (!(stylesheetsPort in worker.ports)){
        return reject(noMatchingPortMessage(stylesheetsModule, stylesheetsPort, worker.ports));
      }

      var stylesheets = worker.ports[stylesheetsPort];

      if (!Array.isArray(stylesheets)){
        return reject(portTypeErrorMessage(stylesheetsModule, stylesheetsPort, stylesheets));
      }

      var failures = stylesheets.filter(function(result) {
        return !result.success;
      });

      return failures.length > 0
      ? reject(reportFailures(failures))
      : resolve(stylesheets);
    });
  };
}

function makeRequirable(dest) {
  return function () {
    return new Promise(function (resolve, reject) {
      // Make the compiled emitter.js Node-friendly.
      fs.appendFile(dest, "\nmodule.exports = Elm;", function(err) {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  }
}

function writeResults(outputDir) {
  return function(results) {
    return Promise.all(
      results.map(writeResult(outputDir))
    );
  };
}

function writeResult(outputDir) {
  return function (result) {
    return new Promise(function(resolve, reject) {
      fs.writeFile(path.join(outputDir, result.filename), result.content + "\n", function(err, file) {
        return err ? reject(err) : resolve(result);
      });
    });
  }
}

function reportFailures(failures) {
  return "The following errors occurred during compilation:\n\n" +
    failures.map(function(result) {
      return result.filename + ": " + result.content;
    }).join("\n\n");
}

function compileEmitter(src, options) {
  return new Promise(function(resolve, reject) {
    compile(src, options)
      .on("close", function(exitCode) {
        if (exitCode === 0) {
          resolve();
        } else {
          reject("Errored with exit code " + exitCode);
        }
      });
  });
}
<|endoftext|>


<commit_before>import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { isSafari } from 'ui/utils/platform';
import layout from './template';
import { next } from '@ember/runloop';
import { get, set, observer, computed } from '@ember/object';
import ThrottledResize from 'shared/mixins/throttled-resize';
import { downloadFile } from 'shared/utils/download-files';
import CodeMirror from 'codemirror';
import jsyaml from 'js-yaml';
import { alias } from '@ember/object/computed'
import C from 'ui/utils/constants';

export default Component.extend(ThrottledResize, {
  settings:         service(),
  growl:            service(),
  scope:            service(),

  layout,
  mode:             'text',
  label:            null,
  namePlaceholder:  '',
  nameRequired:     false,
  name:             null,
  value:            null,
  placeholder:      '',
  accept:           'text/*, .yml, .yaml',
  multiple:         false,
  viewportMargin:   Infinity,
  autoResize:       false,
  resizeFooter:     130,
  minHeight:        50,
  inputName:        false,
  canChangeName:    true,
  canUpload:        true,
  showUploadLabel:  true,
  gutters:          ['CodeMirror-lint-markers'],
  tagName:          ['div'],
  showUpload:       true,
  showDownload:     true,
  deepStr:          null,

  shouldChangeName: true,

  config:        alias('model.config'),

  init() {
    this._super(...arguments);

    window.jsyaml || (window.jsyaml = jsyaml);
  },

  actions: {
    click() {
      this.$('INPUT[type=file]')[0].click();
    },

    wantsChange() {
      set(this, 'shouldChangeName', true);
    },

    download() {
      let yaml = get(this, 'value');
      const lintError = [];

      jsyaml.safeLoadAll(yaml, (y) => {
        lintError.pushObjects(CodeMirror.lint.yaml(y));
      });

      if ( lintError.length ) {
        set(this, 'errors', [get(this, 'intl').t('yamlPage.errors')]);

        return;
      }

      downloadFile(get(this, 'filename'), yaml);
    },

    updateValue(value) {
      next(() => {
        set(this, 'value', value)
      })
    },
  },

  loadingDidChange: observer('loading', function() {
    if ( !get(this, 'loading') && get(this, 'autoResize') ) {
      next(() => {
        this.fit();
      });
    }
  }),

  customTypeObserver: observer('value', function() {
    next(() => {
      const value = get(this, 'value')
      const { fileObj } = this.parseValue(value)
      const type = fileObj['@type']
      const out = C.LOGGING_TPYE_TO_CONFIG[type]

      set(this, 'customType', out)
    })
  }),

  caChange: observer('config.clientKey', 'config.clientCert', 'config.certificate', function() {
    let { fileObj, deepStrs = [] } = this.parseValue(get(this, 'value'));

    delete fileObj.ca_file;
    delete fileObj.client_cert;
    delete fileObj.client_key;
    delete fileObj.ssl_ca_cert;
    delete fileObj.ssl_client_cert;
    delete fileObj.ssl_client_cert_key;
    delete fileObj.tls_cert_path;

    const {
      clientKeyPath = '', clientCertPath = '', certificatePath = ''
    } = this;

    let body = '';
    const caArray = [clientKeyPath, clientCertPath, certificatePath].map((c = '') => {
      const arr = c.split(' ')

      return {
        key:   arr[0],
        value: arr[1],
      }
    })

    caArray.map((c) => {
      if (c.value) {
        fileObj[c.key] = c.value;
      }
    })

    for (let key in fileObj) {
      body += `  ${ key } ${ fileObj[key] }\n`;
    }
    let str = '';

    deepStrs.map((s) => {
      str += s
    })
    const out = `<match *>\n${ body }${ str }</match>`

    this.send('updateValue', out)
  }),

  actualAccept: computed('accept', function() {
    if ( isSafari ) {
      return '';
    } else {
      return get(this, 'accept');
    }
  }),

  logPreview: computed('fieldsStr', function() {
    const fieldsStr = get(this, 'fieldsStr');
    const template = `{
    "log":    "time=\"${ new Date().toString() }\" level=info msg=\"Cluster [local] condition status unknown\"",
    "stream": "stderr",
    "tag":    "default.var.log.containers.cattle-6b4ccb5b9d-v57vw_default_cattle-xxx.log"
    "docker": {
        "container_id": "xxx"
    },
    "kubernetes": {
        "container_name": "cattle",
        "namespace_name": "default",
        "pod_name":       "cattle-6b4ccb5b9d-v57vw",
        "pod_id":         "30c685d0-fa43-11e7-b992-00163e016dc2",
        "labels":         {
            "app": "cattle",
            "pod-template-hash": "2607761658"
        },
        "host":       "47.52.113.251",
        "master_url": "https://10.233.0.1:443/api"
    },
${ fieldsStr }
  ...
}`;

    return template
  }),

  fieldsStr: computed('model.outputTags', function() {
    const keyValueMap = get(this, 'model.outputTags')

    if (!keyValueMap) {
      return '';
    }

    return Object.keys(keyValueMap).map((key) => `    "${ key }": "${ keyValueMap[key] }"`).join(',\n');
  }),

  clientKeyPath: computed('config.clientKey', 'customType', function() {
    const pageScope = get(this, 'pageScope')
    const customType = get(this, 'customType')
    let name

    if (get(this, 'config.clientKey')) {
      if (pageScope === 'cluster') {
        name = get(this, 'scope.currentCluster.id')
      } else {
        const projectId = get(this, 'scope.currentProject.id') || ''

        name = `${ get(this, 'scope.currentCluster.id') }_${ projectId.split(':')[1] }`
      }

      let key = `client_key`

      switch (customType) {
      case 'kafka':
        key = `ssl_client_cert_key`
        break;
      case 'syslog':
        key = `client_cert_key`
        break;
      }

      return `${ key } /fluentd/etc/config/ssl/${ pageScope }_${ name }_client-key.pem`
    }
  }),

  clientCertPath: computed('config.clientCert', 'customType', function() {
    const pageScope = get(this, 'pageScope')
    const customType = get(this, 'customType')
    let name

    if (get(this, 'config.clientCert')) {
      if (pageScope === 'cluster') {
        name = get(this, 'scope.currentCluster.id')
      } else {
        const projectId = get(this, 'scope.currentProject.id') || ''

        name = `${ get(this, 'scope.currentCluster.id') }_${ projectId.split(':')[1] }`
      }

      let key = `client_cert`

      if (customType === 'kafka') {
        key = `ssl_client_cert`
      }

      return `${ key } /fluentd/etc/config/ssl/${ pageScope }_${ name }_client-cert.pem`
    }
  }),

  certificatePath: computed('config.certificate', 'customType', function() {
    const pageScope = get(this, 'pageScope')
    const customType = get(this, 'customType')
    let name

    if (get(this, 'config.certificate')) {
      if (pageScope === 'cluster') {
        name = get(this, 'scope.currentCluster.id')
      } else {
        const projectId = get(this, 'scope.currentProject.id') || ''

        name = `${ get(this, 'scope.currentCluster.id') }_${ projectId.split(':')[1] }`
      }

      let key = `ca_file`

      switch (customType) {
      case 'kafka':
        key = `ssl_ca_cert`
        break;
      case 'fluentForwarder':
        key = `tls_cert_path`
        break;
      }

      return `${ key } /fluentd/etc/config/ssl/${ pageScope }_${ name }_ca.pem`
    }
  }),

  onResize() {
    if ( get(this, 'autoResize') ) {
      this.fit();
    }
  },

  fit() {
    if ( get(this, 'autoResize') ) {
      var container = this.$('.codemirror-container');

      if ( !container ) {
        return;
      }

      const position = container.position();

      if ( !position ) {
        return;
      }

      const desired = this.$(window).height() - position.top - get(this, 'resizeFooter');

      container.css('max-height', Math.max(get(this, 'minHeight'), desired));
    }
  },

  parseValue(value = '') {
    let fileObj = {}
    const removeMacth = value.replace(/.*<match.*>(\r\n|\n|\r) {2}/ig, '').replace(/(\r\n|\n|\r).*<\/match.*>/ig, '')
    const deepStrs = removeMacth.match(/<(.|\r\n|\n|\r)*<\/.*>/ig, '') || []

    const removedDeep = removeMacth.replace(/<(.|\r\n|\n|\r)*<\/.*>/ig, '')

    const myString = removedDeep.replace(/(\r\n|\n|\r)/gm, '
');

    const keyAndValue = myString.split('
').filter((f) => f !== '
').filter((f = '') => !f.startsWith('#') && !f.startsWith('<'))

    keyAndValue.map((item = '') => {
      const arr = item.split(' ').filter((f) => f !== '')

      if (arr[0] && arr[1]) {
        set(fileObj, arr[0], arr[1])
      }
    })

    return {
      fileObj,
      deepStrs
    }
  },

});
<commit_msg>Fix fluentd client cert path and client key path.<commit_after>import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { isSafari } from 'ui/utils/platform';
import layout from './template';
import { next } from '@ember/runloop';
import { get, set, observer, computed } from '@ember/object';
import ThrottledResize from 'shared/mixins/throttled-resize';
import { downloadFile } from 'shared/utils/download-files';
import CodeMirror from 'codemirror';
import jsyaml from 'js-yaml';
import { alias } from '@ember/object/computed'
import C from 'ui/utils/constants';

export default Component.extend(ThrottledResize, {
  settings:         service(),
  growl:            service(),
  scope:            service(),

  layout,
  mode:             'text',
  label:            null,
  namePlaceholder:  '',
  nameRequired:     false,
  name:             null,
  value:            null,
  placeholder:      '',
  accept:           'text/*, .yml, .yaml',
  multiple:         false,
  viewportMargin:   Infinity,
  autoResize:       false,
  resizeFooter:     130,
  minHeight:        50,
  inputName:        false,
  canChangeName:    true,
  canUpload:        true,
  showUploadLabel:  true,
  gutters:          ['CodeMirror-lint-markers'],
  tagName:          ['div'],
  showUpload:       true,
  showDownload:     true,
  deepStr:          null,

  shouldChangeName: true,

  config:        alias('model.config'),

  init() {
    this._super(...arguments);

    window.jsyaml || (window.jsyaml = jsyaml);
  },

  actions: {
    click() {
      this.$('INPUT[type=file]')[0].click();
    },

    wantsChange() {
      set(this, 'shouldChangeName', true);
    },

    download() {
      let yaml = get(this, 'value');
      const lintError = [];

      jsyaml.safeLoadAll(yaml, (y) => {
        lintError.pushObjects(CodeMirror.lint.yaml(y));
      });

      if ( lintError.length ) {
        set(this, 'errors', [get(this, 'intl').t('yamlPage.errors')]);

        return;
      }

      downloadFile(get(this, 'filename'), yaml);
    },

    updateValue(value) {
      next(() => {
        set(this, 'value', value)
      })
    },
  },

  loadingDidChange: observer('loading', function() {
    if ( !get(this, 'loading') && get(this, 'autoResize') ) {
      next(() => {
        this.fit();
      });
    }
  }),

  customTypeObserver: observer('value', function() {
    next(() => {
      const value = get(this, 'value')
      const { fileObj } = this.parseValue(value)
      const type = fileObj['@type']
      const out = C.LOGGING_TPYE_TO_CONFIG[type]

      set(this, 'customType', out)
    })
  }),

  caChange: observer('config.clientKey', 'config.clientCert', 'config.certificate', function() {
    let { fileObj, deepStrs = [] } = this.parseValue(get(this, 'value'));

    const deletedField = [
      'ca_file',
      'client_cert',
      'client_key',
      'ssl_ca_cert',
      'ssl_client_cert',
      'ssl_client_cert_key',
      'tls_cert_path',
      'client_cert_key',
      'tls_client_private_key_path',
      'tls_client_cert_path',
    ]

    deletedField.map((d) => delete fileObj[d])

    const {
      clientKeyPath = '', clientCertPath = '', certificatePath = ''
    } = this;

    let body = '';
    const caArray = [clientKeyPath, clientCertPath, certificatePath].map((c = '') => {
      const arr = c.split(' ')

      return {
        key:   arr[0],
        value: arr[1],
      }
    })

    caArray.map((c) => {
      if (c.value) {
        fileObj[c.key] = c.value;
      }
    })

    for (let key in fileObj) {
      body += `  ${ key } ${ fileObj[key] }\n`;
    }
    let str = '';

    deepStrs.map((s) => {
      str += s
    })
    const out = `<match *>\n${ body }${ str }</match>`

    this.send('updateValue', out)
  }),

  actualAccept: computed('accept', function() {
    if ( isSafari ) {
      return '';
    } else {
      return get(this, 'accept');
    }
  }),

  logPreview: computed('fieldsStr', function() {
    const fieldsStr = get(this, 'fieldsStr');
    const template = `{
    "log":    "time=\"${ new Date().toString() }\" level=info msg=\"Cluster [local] condition status unknown\"",
    "stream": "stderr",
    "tag":    "default.var.log.containers.cattle-6b4ccb5b9d-v57vw_default_cattle-xxx.log"
    "docker": {
        "container_id": "xxx"
    },
    "kubernetes": {
        "container_name": "cattle",
        "namespace_name": "default",
        "pod_name":       "cattle-6b4ccb5b9d-v57vw",
        "pod_id":         "30c685d0-fa43-11e7-b992-00163e016dc2",
        "labels":         {
            "app": "cattle",
            "pod-template-hash": "2607761658"
        },
        "host":       "47.52.113.251",
        "master_url": "https://10.233.0.1:443/api"
    },
${ fieldsStr }
  ...
}`;

    return template
  }),

  fieldsStr: computed('model.outputTags', function() {
    const keyValueMap = get(this, 'model.outputTags')

    if (!keyValueMap) {
      return '';
    }

    return Object.keys(keyValueMap).map((key) => `    "${ key }": "${ keyValueMap[key] }"`).join(',\n');
  }),

  clientKeyPath: computed('config.clientKey', 'customType', function() {
    const pageScope = get(this, 'pageScope')
    const customType = get(this, 'customType')
    let name

    if (get(this, 'config.clientKey')) {
      if (pageScope === 'cluster') {
        name = get(this, 'scope.currentCluster.id')
      } else {
        const projectId = get(this, 'scope.currentProject.id') || ''

        name = `${ get(this, 'scope.currentCluster.id') }_${ projectId.split(':')[1] }`
      }

      let key = `client_key`

      switch (customType) {
      case 'kafka':
        key = `ssl_client_cert_key`
        break;
      case 'syslog':
        key = `client_cert_key`
        break;
      case 'fluentForwarder':
        key = `tls_client_private_key_path`
        break;
      }

      return `${ key } /fluentd/etc/config/ssl/${ pageScope }_${ name }_client-key.pem`
    }
  }),

  clientCertPath: computed('config.clientCert', 'customType', function() {
    const pageScope = get(this, 'pageScope')
    const customType = get(this, 'customType')
    let name

    if (get(this, 'config.clientCert')) {
      if (pageScope === 'cluster') {
        name = get(this, 'scope.currentCluster.id')
      } else {
        const projectId = get(this, 'scope.currentProject.id') || ''

        name = `${ get(this, 'scope.currentCluster.id') }_${ projectId.split(':')[1] }`
      }

      let key = `client_cert`

      switch (customType) {
      case 'kafka':
        key = `ssl_client_cert`
        break;
      case 'fluentForwarder':
        key = `tls_client_cert_path`
        break;
      }

      return `${ key } /fluentd/etc/config/ssl/${ pageScope }_${ name }_client-cert.pem`
    }
  }),

  certificatePath: computed('config.certificate', 'customType', function() {
    const pageScope = get(this, 'pageScope')
    const customType = get(this, 'customType')
    let name

    if (get(this, 'config.certificate')) {
      if (pageScope === 'cluster') {
        name = get(this, 'scope.currentCluster.id')
      } else {
        const projectId = get(this, 'scope.currentProject.id') || ''

        name = `${ get(this, 'scope.currentCluster.id') }_${ projectId.split(':')[1] }`
      }

      let key = `ca_file`

      switch (customType) {
      case 'kafka':
        key = `ssl_ca_cert`
        break;
      case 'fluentForwarder':
        key = `tls_cert_path`
        break;
      }

      return `${ key } /fluentd/etc/config/ssl/${ pageScope }_${ name }_ca.pem`
    }
  }),

  onResize() {
    if ( get(this, 'autoResize') ) {
      this.fit();
    }
  },

  fit() {
    if ( get(this, 'autoResize') ) {
      var container = this.$('.codemirror-container');

      if ( !container ) {
        return;
      }

      const position = container.position();

      if ( !position ) {
        return;
      }

      const desired = this.$(window).height() - position.top - get(this, 'resizeFooter');

      container.css('max-height', Math.max(get(this, 'minHeight'), desired));
    }
  },

  parseValue(value = '') {
    let fileObj = {}
    const removeMacth = value.replace(/.*<match.*>(\r\n|\n|\r) {2}/ig, '').replace(/(\r\n|\n|\r).*<\/match.*>/ig, '')
    const deepStrs = removeMacth.match(/<(.|\r\n|\n|\r)*<\/.*>/ig, '') || []

    const removedDeep = removeMacth.replace(/<(.|\r\n|\n|\r)*<\/.*>/ig, '')

    const myString = removedDeep.replace(/(\r\n|\n|\r)/gm, '
');

    const keyAndValue = myString.split('
').filter((f) => f !== '
').filter((f = '') => !f.startsWith('#') && !f.startsWith('<'))

    keyAndValue.map((item = '') => {
      const arr = item.split(' ').filter((f) => f !== '')

      if (arr[0] && arr[1]) {
        set(fileObj, arr[0], arr[1])
      }
    })

    return {
      fileObj,
      deepStrs
    }
  },

});
<|endoftext|>


<commit_before>'use strict';

const RtmClient = require('@slack/client').RtmClient;
  const CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;
  const RTM_EVENTS = require('@slack/client').RTM_EVENTS;
const WebClient = require('@slack/client').WebClient;
const Time = require('./time')
const NodeCache = require( "node-cache" );

const token = process.env.SLACK_BOT_TOKEN || '';
const rtm = new RtmClient(token)
const web = new WebClient(token)

const cache = new NodeCache({ stdTTL: 30*60, checkperiod: 15*60 });

function getChannelInfo(channelID) {
  const cached = cache.get(channelID)
  if (cached != undefined) {
    console.log(`Got cached info for channel ${channelID}`)
    return Promise.resolve(cached)
  } else {
    return web.channels.info(channelID).catch((error) => {
      if (error.message == 'channel_not_found') {
        console.log(`[DEBUG] ${channelID} may be a private channel; trying to look that up…`)
        return web.groups.info(channelID)
      } else {
        console.log(`Cannot recover from error looking up ${channelID}: ${error}`)
      }
    }).then((response) => {
      const channelInfo = response.channel != undefined ? response.channel : response.group
      const channelCacheTTL = 1 * 60 * 60 // 1 hour, in seconds
      cache.set(channelID, channelInfo, channelCacheTTL)
      return channelInfo
    })
  }
}

function getUserInfo(userID) {
  const cached = cache.get(userID)
  if (cached != undefined) {
    console.log(`Got cached info for user ${userID}`)
    return Promise.resolve(cached)
  } else {
    return web.users.info(userID).then((response) => {
      const userInfo = response.user
      const userCacheTTL = 4 * 60 * 60 // 4 hours, in seconds
      cache.set(userID, userInfo, userCacheTTL)
      return userInfo
    })
  }
}

function pushUniqueZone(zones, zone) {
  if (zones.find((element, idx, array) => { return element.tz_label == zone.tz_label }) == undefined) {
    zones.push(zone)
  }
}

function removeZone(zones, zone) {
  const idx = zones.findIndex((element, idx, array) => { return element.tz_label == zone.tz_label })
  if (idx > -1) {
    zones.splice(idx, 1)
  }
}

rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (rtmStartData) => {
  console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}`)
})

rtm.on(RTM_EVENTS.MESSAGE, (message) => {
  const localTime = Time.parseTime(message.text)
  if (localTime === null) return

  console.log(`[DEBUG] Got message with time ${Time.formatTime(localTime)} in channel ${message.channel}`)

  getChannelInfo(message.channel).then((channel) => {
    var usersToLookup = channel.members.slice(0)
    if (!usersToLookup.includes(message.user)) {
      usersToLookup.push(message.user)
    }

    Promise.all(usersToLookup.map((userID) => { return getUserInfo(userID) })).then((users) => {
      var targetZones = []
      var localZone

      users.forEach((user) => {
        if (user.is_bot) return

        const userZone = {
          'tz_label': user.tz_label,
          'tz_offset': user.tz_offset
        }

        if (userZone.tz_offset == undefined || userZone.tz_label == undefined) return

        if (user.id == message.user) {
          localZone = userZone
        } else {
          pushUniqueZone(targetZones, userZone)
        }
      })

      removeZone(targetZones, localZone)

      if (targetZones.length == 0) return

      targetZones.sort((a, b) => {
        return a.tz_offset - b.tz_offset
      })

      var reply = `*${Time.formatTime(localTime)}* in ${localZone.tz_label} is:`
      targetZones.forEach((zone) => {
        const offsetFromLocal = zone.tz_offset - localZone.tz_offset
        reply = reply + `\n${Time.formatTime(Time.applyOffsetToTime(localTime, offsetFromLocal))} in ${zone.tz_label}`
      })

      rtm.sendMessage(reply, message.channel)
    })
  })
})

rtm.start()
<commit_msg>don't reply to file share messages<commit_after>'use strict';

const RtmClient = require('@slack/client').RtmClient;
  const CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;
  const RTM_EVENTS = require('@slack/client').RTM_EVENTS;
const WebClient = require('@slack/client').WebClient;
const Time = require('./time')
const NodeCache = require( "node-cache" );

const token = process.env.SLACK_BOT_TOKEN || '';
const rtm = new RtmClient(token)
const web = new WebClient(token)

const cache = new NodeCache({ stdTTL: 30*60, checkperiod: 15*60 });

function getChannelInfo(channelID) {
  const cached = cache.get(channelID)
  if (cached != undefined) {
    console.log(`Got cached info for channel ${channelID}`)
    return Promise.resolve(cached)
  } else {
    return web.channels.info(channelID).catch((error) => {
      if (error.message == 'channel_not_found') {
        console.log(`[DEBUG] ${channelID} may be a private channel; trying to look that up…`)
        return web.groups.info(channelID)
      } else {
        console.log(`Cannot recover from error looking up ${channelID}: ${error}`)
      }
    }).then((response) => {
      const channelInfo = response.channel != undefined ? response.channel : response.group
      const channelCacheTTL = 1 * 60 * 60 // 1 hour, in seconds
      cache.set(channelID, channelInfo, channelCacheTTL)
      return channelInfo
    })
  }
}

function getUserInfo(userID) {
  const cached = cache.get(userID)
  if (cached != undefined) {
    console.log(`Got cached info for user ${userID}`)
    return Promise.resolve(cached)
  } else {
    return web.users.info(userID).then((response) => {
      const userInfo = response.user
      const userCacheTTL = 4 * 60 * 60 // 4 hours, in seconds
      cache.set(userID, userInfo, userCacheTTL)
      return userInfo
    })
  }
}

function pushUniqueZone(zones, zone) {
  if (zones.find((element, idx, array) => { return element.tz_label == zone.tz_label }) == undefined) {
    zones.push(zone)
  }
}

function removeZone(zones, zone) {
  const idx = zones.findIndex((element, idx, array) => { return element.tz_label == zone.tz_label })
  if (idx > -1) {
    zones.splice(idx, 1)
  }
}

rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (rtmStartData) => {
  console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}`)
})

rtm.on(RTM_EVENTS.MESSAGE, (message) => {
  const localTime = Time.parseTime(message.text)
  if (localTime === null) return
  if (message.subtype == 'file_share') return

  console.log(`[DEBUG] Got message with time ${Time.formatTime(localTime)} in channel ${message.channel}`)

  getChannelInfo(message.channel).then((channel) => {
    var usersToLookup = channel.members.slice(0)
    if (!usersToLookup.includes(message.user)) {
      usersToLookup.push(message.user)
    }

    Promise.all(usersToLookup.map((userID) => { return getUserInfo(userID) })).then((users) => {
      var targetZones = []
      var localZone

      users.forEach((user) => {
        if (user.is_bot) return

        const userZone = {
          'tz_label': user.tz_label,
          'tz_offset': user.tz_offset
        }

        if (userZone.tz_offset == undefined || userZone.tz_label == undefined) return

        if (user.id == message.user) {
          localZone = userZone
        } else {
          pushUniqueZone(targetZones, userZone)
        }
      })

      removeZone(targetZones, localZone)

      if (targetZones.length == 0) return

      targetZones.sort((a, b) => {
        return a.tz_offset - b.tz_offset
      })

      var reply = `*${Time.formatTime(localTime)}* in ${localZone.tz_label} is:`
      targetZones.forEach((zone) => {
        const offsetFromLocal = zone.tz_offset - localZone.tz_offset
        reply = reply + `\n${Time.formatTime(Time.applyOffsetToTime(localTime, offsetFromLocal))} in ${zone.tz_label}`
      })

      rtm.sendMessage(reply, message.channel)
    })
  })
})

rtm.start()
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var merge = require('lodash/merge');
var spawn = require('child_process').spawn;
var fsExtra = require('fs-extra');

function Plugin(translationOptions) {
  var defaultOptions = {
    conf: './jsdoc.conf'
  };

  this.options = merge({}, defaultOptions, translationOptions);
}

Plugin.prototype.apply = function (compiler) {
  var self = this;
  var options = self.options;

  compiler.plugin('watch-run', function (watching, callback) {
    self.webpackIsWatching = true;
    callback(null, null);
  });

  compiler.plugin('emit', function (compilation, callback) {
    console.log('JSDOC Start generating');

    fsExtra.readJson(path.resolve(process.cwd(), options.conf), function (err, obj) {
      var files = [], jsdocErrors = [];
      var jsdoc, cwd = process.cwd();

      if(err) {
        callback(err);
        return;
      }

      if (obj.source && obj.source.include) {
        console.log('Taking sources from config file');
      } else {
        compilation.chunks.forEach(function (chunk) {
          chunk.modules.forEach(function (module) {
            if (module.fileDependencies) {
              module.fileDependencies.forEach(function (filepath) {
                files.push(path.relative(process.cwd(), filepath));
              });
            }
          });
        });
        merge(obj.source, { include: files });
      }

      var jsDocConfTmp = path.resolve(cwd, 'jsdoc.' + Date.now() + '.conf.tmp');
      fs.writeFileSync(jsDocConfTmp, JSON.stringify(obj));

      jsdoc = spawn('./node_modules/.bin/jsdoc', files.concat('-c', jsDocConfTmp));

      jsdoc.stdout.on('data', function (data) {
        console.log(data.toString());
      });

      jsdoc.stderr.on('data', function (data) {
        jsdocErrors.push(data.toString());
      });

      jsdoc.on('close', function (data, code) {
        if(jsdocErrors.length > 0) {
          jsdocErrors.forEach(function (value) {
            console.error(value);
          });
        } else {
          console.log('JsDoc successful');
        }
        fs.unlink(jsDocConfTmp, function() {
          callback();
        });
      });
    });
  });

  compiler.plugin('done', function (stats) {
    console.log('JSDOC Finished generating');
    console.log('JSDOC TOTAL TIME:', stats.endTime - stats.startTime);
  });
};

module.exports = Plugin;
<commit_msg>Why to concat on variable files here<commit_after>var fs = require('fs');
var path = require('path');
var merge = require('lodash/merge');
var spawn = require('child_process').spawn;
var fsExtra = require('fs-extra');

function Plugin(translationOptions) {
  var defaultOptions = {
    conf: './jsdoc.conf'
  };

  this.options = merge({}, defaultOptions, translationOptions);
}

Plugin.prototype.apply = function (compiler) {
  var self = this;
  var options = self.options;

  compiler.plugin('watch-run', function (watching, callback) {
    self.webpackIsWatching = true;
    callback(null, null);
  });

  compiler.plugin('emit', function (compilation, callback) {
    console.log('JSDOC Start generating');

    fsExtra.readJson(path.resolve(process.cwd(), options.conf), function (err, obj) {
      var files = [], jsdocErrors = [];
      var jsdoc, cwd = process.cwd();

      if(err) {
        callback(err);
        return;
      }

      if (obj.source && obj.source.include) {
        console.log('Taking sources from config file');
      } else {
        compilation.chunks.forEach(function (chunk) {
          chunk.modules.forEach(function (module) {
            if (module.fileDependencies) {
              module.fileDependencies.forEach(function (filepath) {
                files.push(path.relative(process.cwd(), filepath));
              });
            }
          });
        });
        merge(obj.source, { include: files });
      }

      var jsDocConfTmp = path.resolve(cwd, 'jsdoc.' + Date.now() + '.conf.tmp');
      fs.writeFileSync(jsDocConfTmp, JSON.stringify(obj));

      jsdoc = spawn('./node_modules/.bin/jsdoc', ['-c', jsDocConfTmp]);

      jsdoc.stdout.on('data', function (data) {
        console.log(data.toString());
      });

      jsdoc.stderr.on('data', function (data) {
        jsdocErrors.push(data.toString());
      });

      jsdoc.on('close', function (data, code) {
        if(jsdocErrors.length > 0) {
          jsdocErrors.forEach(function (value) {
            console.error(value);
          });
        } else {
          console.log('JsDoc successful');
        }
        fs.unlink(jsDocConfTmp, function() {
          callback();
        });
      });
    });
  });

  compiler.plugin('done', function (stats) {
    console.log('JSDOC Finished generating');
    console.log('JSDOC TOTAL TIME:', stats.endTime - stats.startTime);
  });
};

module.exports = Plugin;
<|endoftext|>