<commit_before>var EventEmitter = require('events').EventEmitter;
var fingerprint = require('./fingerprint');

// create a composition cache
var moduleInstanceCache = engine.cache.comp('moduleInstances', factory);

// module instance cache
engine.modules = {};

// listen to the core load module instance configuration event
engine.on('load', load);

// export methods
exports.access = checkAccess;
exports.factory = factory;

// check if role has access to instance and operation
function checkAccess (role, module_instance, event) {

    // get instance with role check
    module_instance = moduleInstanceCache.get(module_instance, role);

    // check if this instance has acces to the requested operation
    if (module_instance && module_instance._access[event]) {
        return instance;
    }

    return;
}

function linkHandler (link) {
    var self = this;

    // listen to event
    self[link['1'] ? 'once' : 'on'](link.event, function (event, data, callback) {
        self = this;

        // emit or call on a different instance
        // TODO check role access!
        if (link.to) {
            self = compInstances.pojo.get(link.to, event.session.role);
            if (!self) {
                return;
            }
        }

        // create an empty data object
        if (!data && (link.data || link.set)) {
            data = {};
        }

        // handle static data
        if (link.data) {

            // create copy
            try {
                var copy = JSON.parse(JSON.stringify(link.data));

                // merge static data in data
                for (var key in copy) {
                    data[key] = copy[key];
                }
            } catch (err) {

                // websocket requests
                if (event.ws) {
                    return callback(err);
                }

                // http requests
                return callback(500, err);
            }
        }

        // add dynamic data to the data object
        if (link.set) {
            for (var prop in link.set) {
                data[prop] = engine.path(link.set[prop], self);
            }
        }

        // handle method call
        if (link.call) {

            if (typeof link.call === 'string') {
                link.call = engine.path(link.call, self) || link.call;
            }

            if (typeof link.call !== 'function') {

                var err = new Error('links: Cannot find module method: ' + link.call);

                // websocket requests
                if (event.ws) {
                    return event.send(err);
                }

                // http requests
                return event.send(500, err);
            }

            // call linked method
            link.call.call(self, event, data, callback);
        }

        // emit event
        if (link.emit) {
            self.emit(link.emit, event, data, callback);
        }
    });

    // ensure clinet send array
    if (!self._client.send) {
        self._client.send = [];
    }

    // add send events to client
    self._client.send.push(link.event);
    self._access[link.event] = true;
}

// set up link configuration
function linkSetup (instance, links, callback) {

    // set up links
    for (var i = 0, link; i < links.length; ++i) {
        linkHandler.call(instance, links[i]);
    }

    callback(null, instance._client);
}

// create instance
function factory (composition, callback) {

    // create new Mono observer instance
    var instance = new EventEmitter();
    instance._module = module.name ? module.name.replace(/_/g, '/') + '/' : 'c';
    instance._name = compInst.name;
    instance._access = {};
    instance._roles = compInst.roles || {};
    instance._client = {};

    // save configs on instance
    if (compInst.config) {

        // save custom client config
        if (compInst.config.client) {
            instance._client = {
                config: compInst.config.client
            };
        }

        // server config
        instance._config = compInst.config.server || {};
    }

    // save observe infos in client
    if (compInst.flow) {
        instance._client.flow = compInst.flow;
    }

    // save module name in client config
    instance._client.module = instance._module;

    // merge scripts
    // all dependencies of the instance dependencies must be in this array!
    // while installing a module, save all dependencies in the module deps
    // dependencies: ['./file.js', 's/o/modA/v']
    // => ModA deps: ['./file.js', 's/o/modB/v'] => ModB deps: []
    // => to client: ['./file.js', 's/o/n/v/file.js']

    // append module depedency scripts
    if (module.dependencies) {
        instance._client.scripts = module.dependencies.concat(compInst.scripts || []);

    // append instance scripts
    } else if (compInst.scripts) {
        instance._client.scripts = compInst.scripts;
    }

    // TODO better do callback buffering on instances, then copy the scripts
    instance._scripts = instance._client.scripts ? instance._client.scripts.slice() : [];

    // save load infos in client
    if (compInst.load) {
        instance._client.load = compInst.load;
    }

    // attach create link hander method to instance
    instance._link = linkHandler;

    // handle send configurations
    if (!compInst.links) {
        compInst.links = [];
    }

    // attach the broadcast functionality
    //instance._broadcast = broadcast;

    // add fingerprints to scripts
    fingerprint.addToFiles(instance._module, instance._scripts, function (err, scripts) {

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

        // update scripts
        instance._client.scripts = scripts;

        // send original instance name to client, in case it's an alias
        if (compInst.name !== name) {
            instance._client.name = compInst.name;

            // save instance also under original name
            compInstances.pojo.set(compInst.name, instance);
        }

        // configure client main file
        if (module.clientMain) {
            instance._client.main = module.clientMain;
        }

        // save instance in cache
        compInstances.pojo.set(name, instance);

        // require and init module
        if (module.main) {

            try {

                // get absolute path from the repo and relative path from the module
                var path = module.main[0] === '/' ? env.Z_PATH_PROCESS_REPO : env.Z_PATH_PROCESS_MODULES + instance._module;
                var monoModule = require(path + module.main);

                if (typeof monoModule === 'function') {
                    monoModule.call(instance, instance._config || {}, function (err) {

                        if (err) {

                            // remove instance from cache
                            compInstances.pojo.rm(name);

                            return callback(err);
                        }

                        // setup links
                        if (compInst.links) {
                            return linkSetup(instance, compInst.links, callback);
                        }

                        callback(null, instance._client);
                    });
                }
            } catch (err) {

                // remove instance from cache
                compInstances.pojo.rm(name);

                callback('Module ' + compInst.name + ' init error: ' + err.toString());
            }
        } else {

            // setup links
            if (compInst.links) {
                return linkSetup(instance, compInst.links, callback);
            }

            callback(null, instance._client);
        }
    }, true);
}

// load instance configuration (ws)
function load (link) {
    var self = this;

    // receive data
    link.data(function (err, module_instance_name) {

        // load entrypoint module instance with hostname
        if (!module_instance_name) {

            module_instance_name = link.socket.upgradeReq.headers.host.split(':')[0].replace(/\./g, '_');

            // get the public version of the start instance
            if (!link.role) {
                module_instance_name += '.pub';
            }
        }

        // get the module instance
        moduleInstanceCache.get(module_instance_name, link.role, function (err, module_instance) {

            // handle error
            if (err || !module_instance) {
                return link.end('Module instance "' + module_instance_name + '" ' + err || 'not found.');
            }

            // end link and send data
            link.end(null, module_instance._client);
        });
    });
}
<commit_msg>new module instance factory<commit_after>var EventEmitter = require('events').EventEmitter;
var fingerprint = require('./fingerprint');

// create a composition cache
var moduleInstanceCache = engine.cache.comp('moduleInstances', factory);

// module instance cache
engine.modules = {};

// listen to the core load module instance configuration event
engine.on('load', load);

// export methods
exports.access = checkAccess;
exports.factory = factory;

// check if role has access to instance and operation
function checkAccess (role, module_instance, event) {

    // get instance with role check
    module_instance = moduleInstanceCache.get(module_instance, role);

    // check if this instance has acces to the requested operation
    if (module_instance && module_instance._access[event]) {
        return instance;
    }

    return;
}

function linkHandler (link) {
    var self = this;

    // listen to event
    self[link['1'] ? 'once' : 'on'](link.event, function (event, data, callback) {
        self = this;

        // emit or call on a different instance
        // TODO check role access!
        if (link.to) {
            self = compInstances.pojo.get(link.to, event.session.role);
            if (!self) {
                return;
            }
        }

        // create an empty data object
        if (!data && (link.data || link.set)) {
            data = {};
        }

        // handle static data
        if (link.data) {

            // create copy
            try {
                var copy = JSON.parse(JSON.stringify(link.data));

                // merge static data in data
                for (var key in copy) {
                    data[key] = copy[key];
                }
            } catch (err) {

                // websocket requests
                if (event.ws) {
                    return callback(err);
                }

                // http requests
                return callback(500, err);
            }
        }

        // add dynamic data to the data object
        if (link.set) {
            for (var prop in link.set) {
                data[prop] = engine.path(link.set[prop], self);
            }
        }

        // handle method call
        if (link.call) {

            if (typeof link.call === 'string') {
                link.call = engine.path(link.call, self) || link.call;
            }

            if (typeof link.call !== 'function') {

                var err = new Error('links: Cannot find module method: ' + link.call);

                // websocket requests
                if (event.ws) {
                    return event.send(err);
                }

                // http requests
                return event.send(500, err);
            }

            // call linked method
            link.call.call(self, event, data, callback);
        }

        // emit event
        if (link.emit) {
            self.emit(link.emit, event, data, callback);
        }
    });

    // ensure clinet send array
    if (!self._client.send) {
        self._client.send = [];
    }

    // add send events to client
    self._client.send.push(link.event);
    self._access[link.event] = true;
}

// set up link configuration
function linkSetup (instance, links, callback) {

    // set up links
    for (var i = 0, link; i < links.length; ++i) {
        linkHandler.call(instance, links[i]);
    }

    callback(null, instance._client);
}

// create instance
function factory (composition, callback) {

    // create new module instance
    var module_instance = new EventEmitter();

    // save composition data on the module instance
    module_instance._name = composition.name;
    module_instance._roles = composition.roles || {};
    module_instance._client = composition.client || {};
    module_instance._config = composition.config || {};

    // create properties
    module_instance._access = {};

    // attach create link method to module instance
    module_instance.link = engine.link;

    // add fingerprints to client side scripts
    fingerprint.addToFiles(composition.module, module_instance._client.scripts, function (err, scripts) {

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

        // update scripts
        module_instance._client.scripts = scripts;

        // require the serverside module
        if (composition.main) {

            try {

                // get absolute path from the repo and relative path from the module
                var path = composition.main === '/' ? env.Z_PATH_PROCESS_REPO : env.Z_PATH_PROCESS_MODULES + instance._module;
                var require_module = require(path + module.main);

                // extend module instance with module methods
                if (require_module) {
                    for (var prop in require_module) {
                        module_instance[prop] = require_module[prop];
                    }
                }

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

        // TODO setup flow

        // return the module instance
        callback(null, module_instance);
    });
}

// load instance configuration (ws)
function load (link) {
    var self = this;

    // receive data
    link.data(function (err, module_instance_name) {

        // load entrypoint module instance with hostname
        if (!module_instance_name) {

            module_instance_name = link.socket.upgradeReq.headers.host.split(':')[0].replace(/\./g, '_');

            // get the public version of the start instance
            if (!link.role) {
                module_instance_name += '.pub';
            }
        }

        // get the module instance
        moduleInstanceCache.get(module_instance_name, link.role, function (err, module_instance) {

            // handle error
            if (err || !module_instance) {
                return link.end('Module instance "' + module_instance_name + '" ' + err || 'not found.');
            }

            // end link and send data
            link.end(null, module_instance._client);
        });
    });
}
<|endoftext|>


<commit_before>'use strict';

let config = require('./config');

const siStrict = /^([-+]?[0-9]+([\.\,][0-9]+)?([eE][+-]?[0-9]+)?)([⁻⁺]?[⁰¹²³⁴⁵⁶⁷⁸⁹]+)?(\^[-+]?[0-9]+)?(\*\*[-+]?[0-9]+)?(\([0-9]+\))?(%?)$/,
      superscriptMap = {
          '⁰': 0,
          '¹': 1,
          '²': 2,
          '³': 3,
          '⁴': 4,
          '⁵': 5,
          '⁶': 6,
          '⁷': 7,
          '⁸': 8,
          '⁹': 9,
          '⁻': '-',
          '⁺': '+'
      };

function superscriptToInt(s) {
    s = Array.from(s, c => superscriptMap[c]).join('');
    return parseInt(s, 10);
}

function parseNumber(s) {
    // Parse the JS number
    let m = s.match(siStrict);
    if (m === null) {
        console.log('invalid SI number "' + s + '"');
        return NaN;
    }

    let number = m[1].replace(',', '.'),
        exponentU = m[4],
        exponentA = m[5],
        exponentF = m[6],
        uncertainty = m[7],
        isPercentage = m[8] == '%',
        v = new config.Number(number);

    // Apply any SI extensions
    if (isPercentage)
        v = v.times(0.01);
    if (exponentU)
        v = v.pow(superscriptToInt(exponentU));
    if (exponentA)
        v = v.pow(Number(exponentA.substr(1)));
    if (exponentF)
        v = v.pow(Number(exponentF.substr(2)));
    if (uncertainty) {
        uncertainty = uncertainty.slice(1, -1);
        let u = number
            .slice(0, -uncertainty.length)
            .replace(/[1-9]/g, '0')
            .concat(uncertainty);
        v = new config.UncertainNumber(v, new config.Number(u));
    }
    return v;
}

/*
 * Force a class to be an SI Number.  In particalar define prototype methods
 * for the standard mathematical operators.
 */

const operators = [
    { symbol: '+', methods: ['plus'], fallback: function(other) { return this + other;} },
    { symbol: '-', methods: ['minus'], fallback: function(other) { return this - other;} },
    { symbol: '*', methods: ['times'], fallback: function(other) { return this * other;} },
    { symbol: '/', methods: ['dividedBy'], fallback: function(other) { return this / other;} },
    { methods: ['abs'], fallback: function() { return Math.abs(this); } },
    { methods: ['pow'], fallback: function(other) { return Math.pow(this, other); } },
    { methods: ['sqrt'], fallback: function() { return this.pow(0.5); } },
];

function applyStandardMethods(siNumber) {
    // Add named operators to the class.
    for (let op of operators) {
        let fn = op.fallback;
        let name = op.methods[0];
        if (typeof siNumber.prototype[name] === 'undefined')
            siNumber.prototype[name] = fn;
    }

    // It can be certain or exact.
    if (typeof siNumber.prototype.isUncertain === 'undefined')
        Number.prototype.isUncertain = function() { return false; };
    if (typeof siNumber.prototype.isExact === 'undefined')
        Number.prototype.isExact = function() { return true; };
}

module.exports.parse = (s) => {
    // Ignore spaces
    s = s.replace(/[\u0020\u00A0\u2000-\u200A\u202F\u2005F]/g, '');

    // Allow a number to be multipled by another number
    let result = null;
    for (let text of s.split('×')) {
        let v = parseNumber(text);
        if (Number.isNaN(v)) return NaN;
        result = result === null ? v : result.times(v);
    }

    return result;
};

module.exports.applyStandards = applyStandardMethods;

/* Make a Number comply to a SI number */
applyStandardMethods(Number);
<commit_msg>Moved standard named operators to math.js<commit_after>'use strict';

let config = require('./config');

const siStrict = /^([-+]?[0-9]+([\.\,][0-9]+)?([eE][+-]?[0-9]+)?)([⁻⁺]?[⁰¹²³⁴⁵⁶⁷⁸⁹]+)?(\^[-+]?[0-9]+)?(\*\*[-+]?[0-9]+)?(\([0-9]+\))?(%?)$/,
      superscriptMap = {
          '⁰': 0,
          '¹': 1,
          '²': 2,
          '³': 3,
          '⁴': 4,
          '⁵': 5,
          '⁶': 6,
          '⁷': 7,
          '⁸': 8,
          '⁹': 9,
          '⁻': '-',
          '⁺': '+'
      };

function superscriptToInt(s) {
    s = Array.from(s, c => superscriptMap[c]).join('');
    return parseInt(s, 10);
}

function parseNumber(s) {
    // Parse the JS number
    let m = s.match(siStrict);
    if (m === null) {
        console.log('invalid SI number "' + s + '"');
        return NaN;
    }

    let number = m[1].replace(',', '.'),
        exponentU = m[4],
        exponentA = m[5],
        exponentF = m[6],
        uncertainty = m[7],
        isPercentage = m[8] == '%',
        v = new config.Number(number);

    // Apply any SI extensions
    if (isPercentage)
        v = v.times(0.01);
    if (exponentU)
        v = v.pow(superscriptToInt(exponentU));
    if (exponentA)
        v = v.pow(Number(exponentA.substr(1)));
    if (exponentF)
        v = v.pow(Number(exponentF.substr(2)));
    if (uncertainty) {
        uncertainty = uncertainty.slice(1, -1);
        let u = number
            .slice(0, -uncertainty.length)
            .replace(/[1-9]/g, '0')
            .concat(uncertainty);
        v = new config.UncertainNumber(v, new config.Number(u));
    }
    return v;
}

module.exports.parse = (s) => {
    // Ignore spaces
    s = s.replace(/[\u0020\u00A0\u2000-\u200A\u202F\u2005F]/g, '');

    // Allow a number to be multipled by another number
    let result = null;
    for (let text of s.split('×')) {
        let v = parseNumber(text);
        if (Number.isNaN(v)) return NaN;
        result = result === null ? v : result.times(v);
    }

    return result;
};
<|endoftext|>


<commit_before>export default function(result, options) {
    const styles = result.styles.map(stylesPath => {
        return `require('${stylesPath}')`;
    }).join('; ');
    const createFactory = `require('react').createFactory`;
    const inject = `module.__yummies__ = module.__yummies__ || {}; module.__yummies__['${result.component}'] = '${result.raw}'`;

    if (options.injectable) {
        if (result.opts.inject === true) {
            if (result.opts.class === true) {
                return `/* ${result.raw} */ function(injects) { return require('@yummies/layers-loader/build/inject!${result.component}')(injects); }; ${styles}`;
            }

            return `/* ${result.raw} */ function(injects) { return ${createFactory}(require('@yummies/layers-loader/build/inject!${result.component}')(injects)); }; ${styles}`;
        }

        if (result.opts.class === true) {
            return `/* ${result.raw} */ (function() {
                ${inject};

                var out = require('${result.component}');

                ${styles};

                return out;
            })()`;
        }

        return `/* ${result.raw} */ (function() {
            ${inject};

            var out = ${createFactory}(
                require('${result.component}')
            );

            ${styles};

            return out;
        })()`;
    }

    if (result.opts.class === true) {
        return `/* ${result.raw} */ require('${result.component}'); ${styles}`;
    }

    return `/* ${result.raw} */ ${createFactory}(require('${result.component}')); ${styles}`;
}
<commit_msg>Fix for export default and webpack<commit_after>export default function(result, options) {
    const styles = result.styles.map(stylesPath => {
        return `require('${stylesPath}')`;
    }).join('; ');
    const createFactory = `require('react').createFactory`;
    const inject = `module.__yummies__ = module.__yummies__ || {}; module.__yummies__['${result.component}'] = '${result.raw}'`;
    const requireEs6 = (path) => `function(obj){ return obj && obj.__esModule ? obj : { \'default\': obj }; }(require('${path}')).default`;

    if (options.injectable) {
        if (result.opts.inject === true) {
            if (result.opts.class === true) {
                return `/* ${result.raw} */ function(injects) { return require('@yummies/layers-loader/build/inject!${result.component}')(injects); }; ${styles}`;
            }

            return `/* ${result.raw} */ function(injects) { return ${createFactory}(${requireEs6(`@yummies/layers-loader/build/inject!${result.component}`)}(injects)); }; ${styles}`;
        }

        if (result.opts.class === true) {
            return `/* ${result.raw} */ (function() {
                ${inject};

                var out = require('${result.component}');

                ${styles};

                return out;
            })()`;
        }

        return `/* ${result.raw} */ (function() {
            ${inject};

            var out = ${createFactory}(${requireEs6(result.component)});

            ${styles};

            return out;
        })()`;
    }

    if (result.opts.class === true) {
        return `/* ${result.raw} */ require('${result.component}'); ${styles}`;
    }

    return `/* ${result.raw} */ ${createFactory}(${requireEs6(result.component)}); ${styles}`;
}
<|endoftext|>


<commit_before>import path from 'path';
import glob from 'glob';
import fs from 'fs';
import async from 'async';

import { MonicError } from './error';
import { FileStructure } from './file';
import { SourceMapConsumer } from 'source-map';

/**
 * Parser class
 */
export default class Parser {
	/**
	 * @param {string} nl - EOL symbol
	 * @param {!Array} replacers - an array of transform functions
	 * @param {boolean} sourceMaps - if is true, then will be enabled support for source maps
	 */
	constructor({nl, replacers, sourceMaps}) {
		this.nl = nl;
		this.replacers = replacers;
		this.sourceMaps = sourceMaps;
		this.realpathCache = {};
		this.cache = {};
	}

	/**
	 * Checks a file for existence
	 * and returns an absolute path to it
	 *
	 * @param {string} file - the file path
	 * @param {function(Error, string=)} callback - a callback function
	 */
	normalizePath(file, callback) {
		file = path.normalize(path.resolve(file));

		if (this.realpathCache[file]) {
			callback(null, file);

		} else {
			async.waterfall([
				(next) => fs.stat(file, next),
				(stat, next) => {
					if (!stat.isFile()) {
						return next(new Error(`"${file}" is not a file`));
					}

					this.realpathCache[file] = true;
					next(null, file);
				}

			], callback);
		}
	}

	/**
	 * Parses a file and returns it structure
	 *
	 * @param {string} file - the file path
	 * @param {function(Error, FileStructure=, string=)} callback - a callback function
	 */
	parseFile(file, callback) {
		async.waterfall([
			(next) => this.normalizePath(file, next),

			(src, next) => {
				if (this.cache[src]) {
					return next(null, src, this.cache[src]);
				}

				fs.readFile(src, (err, content) => {
					next(err, src, String(content));
				});
			},

			(src, content, next) => {
				if (typeof content !== 'string') {
					return next(null, content, src);
				}

				this.parse(src, content, next);
			}

		], callback);
	}

	/**
	 * Parses a text and returns it structure
	 *
	 * @param {string} file - a path to a file
	 * @param {string} content - the source text
	 * @param {function(Error, FileStructure=, string=)} callback - a callback function
	 */
	parse(file, content, callback) {
		if (this.cache[file]) {
			return callback(null, this.cache[file], file);
		}

		const
			actions = [],
			dirname = path.dirname(file);

		content = $C(this.replacers).reduce((content, el) => {
			content = el(content, file);
			return content;

		}, content);

		// URL transformers
		content = content.replace(/^([^\S\n\r]*\/\/(?:#include|without)\s+)(.*)/gm, (sstr, decl, src) => {
			actions.push((cb) => {
				const parts = src.split('::');
				glob(path.join(dirname, parts[0]), null, (err, files) => {
					if (files) {
						content = content.replace(sstr, $C(files).reduce((res, el) => {
							parts[0] = path.relative(dirname, el);
							res += decl + parts.join('::') + this.nl;
							return res;
						}, ''));
					}

					cb(err, files);
				});
			});

			return sstr;
		});

		let sourceMap;
		if (this.sourceMaps) {
			content = content.replace(/\/\/# sourceMappingURL=(.*?)\s*$/, (sstr, url) => {
				actions.push((cb) => {
					fs.readFile(path.normalize(path.resolve(path.dirname(file), url)), (err, str) => {
						try {
							sourceMap = new SourceMapConsumer(JSON.parse(str));
							content = content.replace(sstr, this.nl);

						} catch (ignore) {

						} finally {
							cb(null);
						}
					});
				});

				return sstr;
			});
		}

		async.parallel(actions, (err) => {
			if (err) {
				return callback(err);
			}

			const
				fileStructure = new FileStructure({file, nl: this.nl}),
				lines = content.split(/\r?\n|\r/);

			this.cache[file] = fileStructure;
			const parseLines = (start) => {
				const
					errors = [];

				let
					info,
					i;

				function appendError(err) {
					const
						msg = err.message;

					errors.push(new MonicError(msg, file, i + 1));
					fileStructure.error(msg, info);
				}

				function asyncParseCallback(err) {
					if (err) {
						appendError(err);
					}

					parseLines(i + 1);
				}

				let original;
				if (sourceMap) {
					let
						originalMap = [];

					sourceMap.eachMapping((el) => {
						originalMap.push({
							generated: {
								line: el.generatedLine,
								column: el.generatedColumn
							},

							original: {
								line: el.originalLine,
								column: el.originalColumn
							},

							source: el.source,
							name: el.name
						});
					});

					if (sourceMap.sourcesContent) {
						$C(sourceMap.sourcesContent).forEach((content, i) => {
							const
								src = sourceMap.sources[i];

							$C(originalMap).forEach((el) => {
								if (el.source === src) {
									el.sourcesContent = content;
								}
							});
						});
					}

					original = $C(originalMap).group('generated > line');
				}

				for (i = start; i < lines.length; i++) {
					const
						line = lines[i],
						val = line + (i < lines.length - 1 ? this.nl : '');

					if (this.sourceMaps) {
						if (original) {
							info = original[i] || {ignore: true};

						} else {
							info = {
								generated: {
									column: 0
								},

								original: {
									line: i + 1,
									column: 0
								},

								source: file,
								sourcesContent: content,
								line
							};
						}
					}

					if (line.match(/^\s*\/\/#(.*)/)) {
						if (RegExp.$1) {
							const
								command = RegExp.$1.split(' '),
								dir = String(command.shift());

							const
								key = '_' + dir,
								params = command.join(' ');

							if (/^(?:include|without)$/.test(dir)) {
								return this[key](fileStructure, params, asyncParseCallback);

							} else if (/^(?:label|endlabel|if|endif|set|unset)$/.test(dir)) {
								try {
									this[key](fileStructure, params);

								} catch (err) {
									appendError(err);
								}

							} else {
								fileStructure.addCode(val, info);
							}
						}

					} else {
						fileStructure.addCode(val, info);
					}
				}

				callback(null, fileStructure, file);
			};

			parseLines(0);
		});
	}

	/**
	 * Directive #include
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 * @param {function(Error=)} callback - a callback function
	 */
	_include(file, value, callback) {
		let
			paramsParts = value.split('::'),
			includeFileName = paramsParts.shift();

		paramsParts = $C(paramsParts).reduce((res, el) => {
			res[el] = true;
			return res;
		}, {});

		if (includeFileName) {
			this.parseFile(file.getRelativePathOf(includeFileName), (err, includeFile) => {
				if (err) {
					return callback(err);
				}

				file.addInclude(includeFile, paramsParts);
				callback();
			});

		} else {
			$C(paramsParts).forEach((el, key) => {
				file.root.labels[key] = true;
			});

			callback();
		}
	}

	/**
	 * Directive #without
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 * @param {function(Error=)} callback - a callback function
	 */
	_without(file, value, callback) {
		let
			paramsParts = value.split('::'),
			includedFile = file.getRelativePathOf(paramsParts.shift());

		paramsParts = $C(paramsParts).reduce((res, el) => {
			res[el] = true;
			return res;
		}, {});

		this.parseFile(includedFile, (err, includeFile) => {
			if (err) {
				return callback(err);
			}

			file.addWithout(includeFile, paramsParts);
			callback();
		});
	}

	/**
	 * Directive #label
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 */
	_label(file, value) {
		file.beginLabel(value);
	}

	/**
	 * Directive #endlabel
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 */
	_endlabel(file) {
		file.endLabel();
	}

	/**
	 * Directive #if
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 */
	_if(file, value) {
		value = value.trim();

		if (!value) {
			throw new Error('Bad "if" directive');
		}

		const
			args = value.split(/\s+/);

		let res = true;
		if (args.length > 1 && args[0] === 'not') {
			res = false;
			args.shift();
		}

		file.beginIf(args[0], res);
	}

	/**
	 * Directive #endif
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 */
	_endif(file) {
		file.endIf();
	}

	/**
	 * Directive #set
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 */
	_set(file, value) {
		value = value.trim();

		if (!value) {
			throw new Error('Bad "set" directive');
		}

		file.addSet(value);
	}

	/**
	 * Directive #unset
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 */
	_unset(file, value) {
		value = value.trim();

		if (!value) {
			throw new Error('Bad "unset" directive');
		}

		file.addUnset(value);
	}
}
<commit_msg>Bugfix<commit_after>import path from 'path';
import glob from 'glob';
import fs from 'fs';
import async from 'async';

import { MonicError } from './error';
import { FileStructure } from './file';
import { SourceMapConsumer } from 'source-map';

/**
 * Parser class
 */
export default class Parser {
	/**
	 * @param {string} nl - EOL symbol
	 * @param {!Array} replacers - an array of transform functions
	 * @param {boolean} sourceMaps - if is true, then will be enabled support for source maps
	 */
	constructor({nl, replacers, sourceMaps}) {
		this.nl = nl;
		this.replacers = replacers;
		this.sourceMaps = sourceMaps;
		this.realpathCache = {};
		this.cache = {};
	}

	/**
	 * Checks a file for existence
	 * and returns an absolute path to it
	 *
	 * @param {string} file - the file path
	 * @param {function(Error, string=)} callback - a callback function
	 */
	normalizePath(file, callback) {
		file = path.normalize(path.resolve(file));

		if (this.realpathCache[file]) {
			callback(null, file);

		} else {
			async.waterfall([
				(next) => fs.stat(file, next),
				(stat, next) => {
					if (!stat.isFile()) {
						return next(new Error(`"${file}" is not a file`));
					}

					this.realpathCache[file] = true;
					next(null, file);
				}

			], callback);
		}
	}

	/**
	 * Parses a file and returns it structure
	 *
	 * @param {string} file - the file path
	 * @param {function(Error, FileStructure=, string=)} callback - a callback function
	 */
	parseFile(file, callback) {
		async.waterfall([
			(next) => this.normalizePath(file, next),

			(src, next) => {
				if (this.cache[src]) {
					return next(null, src, this.cache[src]);
				}

				fs.readFile(src, (err, content) => {
					next(err, src, String(content));
				});
			},

			(src, content, next) => {
				if (typeof content !== 'string') {
					return next(null, content, src);
				}

				this.parse(src, content, next);
			}

		], callback);
	}

	/**
	 * Parses a text and returns it structure
	 *
	 * @param {string} file - a path to a file
	 * @param {string} content - the source text
	 * @param {function(Error, FileStructure=, string=)} callback - a callback function
	 */
	parse(file, content, callback) {
		if (this.cache[file]) {
			return callback(null, this.cache[file], file);
		}

		const
			actions = [],
			dirname = path.dirname(file);

		content = $C(this.replacers).reduce((content, el) => {
			content = el(content, file);
			return content;

		}, content);

		// URL transformers
		content = content.replace(/^([^\S\n\r]*\/\/(?:#include|without)\s+)(.*)/gm, (sstr, decl, src) => {
			actions.push((cb) => {
				const parts = src.split('::');
				glob(path.join(dirname, parts[0]), null, (err, files) => {
					if (files) {
						content = content.replace(sstr, $C(files).reduce((res, el, i) => {
							parts[0] = path.relative(dirname, el);
							res += decl + parts.join('::') + (files.length > 1 && i !== files.length - 1 ? this.nl : '');
							return res;
						}, ''));
					}

					cb(err, files);
				});
			});

			return sstr;
		});

		let sourceMap;
		if (this.sourceMaps) {
			content = content.replace(/\/\/# sourceMappingURL=(.*?)\s*$/, (sstr, url) => {
				actions.push((cb) => {
					fs.readFile(path.normalize(path.resolve(path.dirname(file), url)), (err, str) => {
						try {
							sourceMap = new SourceMapConsumer(JSON.parse(str));
							content = content.replace(sstr, this.nl);

						} catch (ignore) {

						} finally {
							cb(null);
						}
					});
				});

				return sstr;
			});
		}

		async.parallel(actions, (err) => {
			if (err) {
				return callback(err);
			}

			const
				fileStructure = new FileStructure({file, nl: this.nl}),
				lines = content.split(/\r?\n|\r/);

			this.cache[file] = fileStructure;
			const parseLines = (start) => {
				const
					errors = [];

				let
					info,
					i;

				function appendError(err) {
					const
						msg = err.message;

					errors.push(new MonicError(msg, file, i + 1));
					fileStructure.error(msg, info);
				}

				function asyncParseCallback(err) {
					if (err) {
						appendError(err);
					}

					parseLines(i + 1);
				}

				let original;
				if (sourceMap) {
					let
						originalMap = [];

					sourceMap.eachMapping((el) => {
						originalMap.push({
							generated: {
								line: el.generatedLine,
								column: el.generatedColumn
							},

							original: {
								line: el.originalLine,
								column: el.originalColumn
							},

							source: el.source,
							name: el.name
						});
					});

					if (sourceMap.sourcesContent) {
						$C(sourceMap.sourcesContent).forEach((content, i) => {
							const
								src = sourceMap.sources[i];

							$C(originalMap).forEach((el) => {
								if (el.source === src) {
									el.sourcesContent = content;
								}
							});
						});
					}

					original = $C(originalMap).group('generated > line');
				}

				for (i = start; i < lines.length; i++) {
					const
						line = lines[i],
						val = line + (i < lines.length - 1 ? this.nl : '');

					if (this.sourceMaps) {
						if (original) {
							info = original[i] || {ignore: true};

						} else {
							info = {
								generated: {
									column: 0
								},

								original: {
									line: i + 1,
									column: 0
								},

								source: file,
								sourcesContent: content,
								line
							};
						}
					}

					if (line.match(/^\s*\/\/#(.*)/)) {
						if (RegExp.$1) {
							const
								command = RegExp.$1.split(' '),
								dir = String(command.shift());

							const
								key = '_' + dir,
								params = command.join(' ');

							if (/^(?:include|without)$/.test(dir)) {
								return this[key](fileStructure, params, asyncParseCallback);

							} else if (/^(?:label|endlabel|if|endif|set|unset)$/.test(dir)) {
								try {
									this[key](fileStructure, params);

								} catch (err) {
									appendError(err);
								}

							} else {
								fileStructure.addCode(val, info);
							}
						}

					} else {
						fileStructure.addCode(val, info);
					}
				}

				callback(null, fileStructure, file);
			};

			parseLines(0);
		});
	}

	/**
	 * Directive #include
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 * @param {function(Error=)} callback - a callback function
	 */
	_include(file, value, callback) {
		let
			paramsParts = value.split('::'),
			includeFileName = paramsParts.shift();

		paramsParts = $C(paramsParts).reduce((res, el) => {
			res[el] = true;
			return res;
		}, {});

		if (includeFileName) {
			this.parseFile(file.getRelativePathOf(includeFileName), (err, includeFile) => {
				if (err) {
					return callback(err);
				}

				file.addInclude(includeFile, paramsParts);
				callback();
			});

		} else {
			$C(paramsParts).forEach((el, key) => {
				file.root.labels[key] = true;
			});

			callback();
		}
	}

	/**
	 * Directive #without
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 * @param {function(Error=)} callback - a callback function
	 */
	_without(file, value, callback) {
		let
			paramsParts = value.split('::'),
			includedFile = file.getRelativePathOf(paramsParts.shift());

		paramsParts = $C(paramsParts).reduce((res, el) => {
			res[el] = true;
			return res;
		}, {});

		this.parseFile(includedFile, (err, includeFile) => {
			if (err) {
				return callback(err);
			}

			file.addWithout(includeFile, paramsParts);
			callback();
		});
	}

	/**
	 * Directive #label
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 */
	_label(file, value) {
		file.beginLabel(value);
	}

	/**
	 * Directive #endlabel
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 */
	_endlabel(file) {
		file.endLabel();
	}

	/**
	 * Directive #if
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 */
	_if(file, value) {
		value = value.trim();

		if (!value) {
			throw new Error('Bad "if" directive');
		}

		const
			args = value.split(/\s+/);

		let res = true;
		if (args.length > 1 && args[0] === 'not') {
			res = false;
			args.shift();
		}

		file.beginIf(args[0], res);
	}

	/**
	 * Directive #endif
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 */
	_endif(file) {
		file.endIf();
	}

	/**
	 * Directive #set
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 */
	_set(file, value) {
		value = value.trim();

		if (!value) {
			throw new Error('Bad "set" directive');
		}

		file.addSet(value);
	}

	/**
	 * Directive #unset
	 *
	 * @private
	 * @param {!FileStructure} file - a file structure
	 * @param {string} value - a value of the directive
	 */
	_unset(file, value) {
		value = value.trim();

		if (!value) {
			throw new Error('Bad "unset" directive');
		}

		file.addUnset(value);
	}
}
<|endoftext|>


<commit_before>/**
 *  gitShowBranchParser: a simple tool to parse the output of `git show-branch` into useful JSON
 */
var fs = require('fs');
var Promise = require('rsvp').Promise;
var _ = require('underscore');

module.exports = (function () {
    var createBranchFromLine = function(line) {
        return {
            label: line.match(/\[([^\]]*)\]/)[1],
            latestCommit: line.match(/\] *(.*)/)[1]
        };
    };

    var createCommitFromLine = function(line) {
        return {
            label: line.match(/\[([^\]]*)\]/)[1],
            commitMessage: line.match(/\] *(.*)/)[1],
            branches: line.slice(0, line.indexOf(' [')).split("")
                .map(function(letter){ return letter !== ' '; })
        };
    };

    var readFilePromise = function (path, options) {
        return new Promise(function promiseifyReadFile (res, rej) {
            fs.readFile(
                path,
                options?options:{},
                function handleReadFile (err, data) {
                    if (err) {
                        rej(err);
                    } else {
                        res(data);
                    }
                }
            );
        });
    };

    var parser = function (pathToOutput, callback) {
        return readFilePromise(pathToOutput)
            .then(function parseBuffer (buffer) {
                var lines, splitLines;

                // Read buffer and split into separate lines
                lines = buffer.toString().split('\n');

                // Separate header lines (branches) from rows (commits)
                splitLines = {
                    branchLines : textLines.splice(0, textLines.indexOf('---')),
                    commitLines : textLines.splice(1).filter(function(line){return !line.match(/^ *$/);})
                };

                // Return parsed object
                return {
                    branches: splitLines.branchLines.map(createBranchFromLine),
                    commits: splitLines.commitLines.map(createCommitFromLine)
                };
            }).then ( function executeCallback (processedObj) {
                if (_.isFunction(callback)) {
                    callback(null, processedObj);
                }
                return processedObj;
            }).catch(function catchParseError (err) {
                callback(err);
            });
    };
    /*
    var parser = function (pathToOutput, callback) {
        return readFilePromise(pathToOutput)
            .then(function convertAndSplit (buffer) {
                return buffer.toString().split('\n');
            }).then(function separateBranchesFromCommits (outputLines) {
                return {
                    branchLines : textLines.splice(0, textLines.indexOf('---')),
                    commitLines : textLines.splice(1).filter(function(line){return !line.match(/^ *$/);})
                };
            }).then(function processLines(splitLines) {
                return {
                    branches: splitLines.branchLines.map(createBranchFromLine),
                    commits: splitLines.commitLines.map(createCommitFromLine)
                }
            }).then ( function executeCallback (processedObj) {
                if (_.isFunction(callback) {
                    callback(null, processedObj);
                };
                return processedObj;
            });
    };
    */

    return parser;
})();

<commit_msg>rsvp error handler and bugfixes<commit_after>/**
 *  gitShowBranchParser: a simple tool to parse the output of `git show-branch` into useful JSON
 */
var fs = require('fs');
var RSVP = require('RSVP');
var _ = require('underscore');

module.exports = (function () {
    var Promise = RSVP.Promise;
    RSVP.on('error', function(reason) {
        console.error(reason);
    });
    var createBranchFromLine = function(line) {
        return {
            label: line.match(/\[([^\]]*)\]/)[1],
            latestCommit: line.match(/\] *(.*)/)[1]
        };
    };

    var createCommitFromLine = function(line) {
        return {
            label: line.match(/\[([^\]]*)\]/)[1],
            commitMessage: line.match(/\] *(.*)/)[1],
            branches: line.slice(0, line.indexOf(' [')).split("")
                .map(function(letter){ return letter !== ' '; })
        };
    };

    var readFilePromise = function (path, options) {
        return new Promise(function promiseifyReadFile (res, rej) {
            fs.readFile(
                path,
                options?options:{},
                function handleReadFile (err, data) {
                    if (err) {
                        rej(err);
                    } else {
                        res(data);
                    }
                }
            );
        });
    };

    var parser = function (pathToOutput, callback) {
        return readFilePromise(pathToOutput)
            .then(function parseBuffer (buffer) {
                var lines, splitLines;

                // Read buffer and split into separate lines
                lines = buffer.toString().split('\n');

                // Separate header lines (branches) from rows (commits)
                splitLines = {
                    branchLines : lines.splice(0, lines.indexOf('---')),
                    commitLines : lines.splice(1).filter(function(line){return !line.match(/^ *$/);})
                };

                // Return parsed object
                return {
                    branches: splitLines.branchLines.map(createBranchFromLine),
                    commits: splitLines.commitLines.map(createCommitFromLine)
                };
            }).then ( function executeCallback (processedObj) {
                if (_.isFunction(callback)) {
                    callback(null, processedObj);
                }
                return processedObj;
            }).catch(function catchParseError (err) {
                if (_.isFunction(callback)) {
                    callback(err);
                }
                console.error(err);
                throw err;
            });
    };
    /*
    var parser = function (pathToOutput, callback) {
        return readFilePromise(pathToOutput)
            .then(function convertAndSplit (buffer) {
                return buffer.toString().split('\n');
            }).then(function separateBranchesFromCommits (outputLines) {
                return {
                    branchLines : textLines.splice(0, textLines.indexOf('---')),
                    commitLines : textLines.splice(1).filter(function(line){return !line.match(/^ *$/);})
                };
            }).then(function processLines(splitLines) {
                return {
                    branches: splitLines.branchLines.map(createBranchFromLine),
                    commits: splitLines.commitLines.map(createCommitFromLine)
                }
            }).then ( function executeCallback (processedObj) {
                if (_.isFunction(callback) {
                    callback(null, processedObj);
                };
                return processedObj;
            });
    };
    */

    return parser;
})();

<|endoftext|>


<commit_before>
/**
 * Exposes the client parser to avoid code repetition.
 */

module.exports = require('engine.io-client').parser;
<commit_msg>directly load the parser module<commit_after>/**
 * Exposes the client parser to avoid code repetition.
 */

module.exports = require('engine.io-client/lib/parser');
<|endoftext|>


<commit_before>'use strict';
var postcss, _remgex, _PROPS, _VALUES, _rootvalue, _options;

// Add pixel fallbacks for rem units to a string of CSS
// - css `String`: the contents of a CSS file.
// - rootvalue `String | Null`: The root element font size. Default = 16px.
// - options `Object`
//     - replace `Boolean`: Replace rems with pixels instead of providing
//       fallbacks. Default = false.
//     - atrules `Boolean`: Replace rems in at-rules too. Default = false

function Pixrem (rootvalue, options) {
  postcss = require('postcss');
  _remgex = /(\d*\.?\d+)rem/ig;
  _PROPS  = /^(background-size|border-image|border-radius|box-shadow|clip-path|column|grid|mask|object|perspective|scroll|shape|size|stroke|transform)/;
  _VALUES = /(calc|gradient)\(/;
  _rootvalue = typeof rootvalue !== 'undefined' ? rootvalue : 16;
  _options = typeof options !== 'undefined' ? options : {
    replace: false,
    atrules: false
  };
}

Pixrem.prototype.process = function (css, options) {
  return postcss(this.postcss).process(css, options).css;
};

Pixrem.prototype.postcss = function (css) {

  var vendor = require('postcss/lib/vendor');

  // First, check root font-size
  css.eachRule(function (rule) {
    if (rule.parent.type === 'atrule') { return };
    if (/(html|:root)/.test(rule.selectors)) {
      rule.eachDecl(function (decl) {
        if (decl.prop === 'font-size') {
          _rootvalue = decl.value;
        } else if (decl.prop === 'font' && decl.value.match(/\d/)) {
          _rootvalue = decl.value.match(/.*?([\d\.]*(em|px|rem|%|pt|pc))/)[1];
        }
      });
    }
  });

  //Then, for each rules
  css.eachRule(function (rule) {

    // do not convert rem if in at-rule
    if (!_options.atrules) {
      if (rule.type === 'atrule' || rule.parent.type === 'atrule') { return; }
    }

    rule.eachDecl(function (decl, i) {
      var value = decl.value;

      if (value.indexOf('rem') !== -1) {

        var prop = vendor.unprefixed(decl.prop);
        // replace rems only if needed
        if (!(_VALUES.test(value) || _PROPS.test(prop))) {

          value = value.replace(_remgex, function ($1) {
            // Round decimal pixels down to match webkit and opera behavior:
            // http://tylertate.com/blog/2012/01/05/subpixel-rounding.html
            return Math.floor(parseFloat($1) * toPx(_rootvalue)) + 'px';
          });

          if (_options.replace) {
            decl.value = value;
          } else {
            rule.insertBefore(i, decl.clone({ value: value }));
          }

        }
      }
    });

  });

};

// Return a unitless pixel value from any root font-size value.
function toPx (value) {
  var parts = /^(\d+\.?\d*)([a-zA-Z%]*)$/.exec(value);
  var number = parts[1];
  var unit = parts[2];

  if (unit === 'px' || unit === '') {
    return parseFloat(number);
  }
  else if (unit === 'em' || unit === 'rem') {
    return parseFloat(number) * 16;
  }
  else if (unit === '%') {
    return (parseFloat(number) / 100) * 16;
  }

  // TODO: Should we throw an error here?
  return false;
}

var pixrem = function (rootvalue, options) {
  return new Pixrem(rootvalue, options);
};
pixrem.process = function (css, rootvalue, options, postcssoptions) {
  return new Pixrem(rootvalue, options).process(css, postcssoptions);
};
pixrem.postcss = function (css) {
  return new Pixrem().postcss(css);
};

module.exports = pixrem;
<commit_msg>Fixed: prevent node exception if parent does not exist or is undefined<commit_after>'use strict';
var postcss, _remgex, _PROPS, _VALUES, _rootvalue, _options;

// Add pixel fallbacks for rem units to a string of CSS
// - css `String`: the contents of a CSS file.
// - rootvalue `String | Null`: The root element font size. Default = 16px.
// - options `Object`
//     - replace `Boolean`: Replace rems with pixels instead of providing
//       fallbacks. Default = false.
//     - atrules `Boolean`: Replace rems in at-rules too. Default = false

function Pixrem (rootvalue, options) {
  postcss = require('postcss');
  _remgex = /(\d*\.?\d+)rem/ig;
  _PROPS  = /^(background-size|border-image|border-radius|box-shadow|clip-path|column|grid|mask|object|perspective|scroll|shape|size|stroke|transform)/;
  _VALUES = /(calc|gradient)\(/;
  _rootvalue = typeof rootvalue !== 'undefined' ? rootvalue : 16;
  _options = typeof options !== 'undefined' ? options : {
    replace: false,
    atrules: false
  };
}

Pixrem.prototype.process = function (css, options) {
  return postcss(this.postcss).process(css, options).css;
};

Pixrem.prototype.postcss = function (css) {

  var vendor = require('postcss/lib/vendor');

  // First, check root font-size
  css.eachRule(function (rule) {
    if (rule.parent && rule.parent.type === 'atrule') { return };
    if (/(html|:root)/.test(rule.selectors)) {
      rule.eachDecl(function (decl) {
        if (decl.prop === 'font-size') {
          _rootvalue = decl.value;
        } else if (decl.prop === 'font' && decl.value.match(/\d/)) {
          _rootvalue = decl.value.match(/.*?([\d\.]*(em|px|rem|%|pt|pc))/)[1];
        }
      });
    }
  });

  //Then, for each rules
  css.eachRule(function (rule) {

    // do not convert rem if in at-rule
    if (!_options.atrules) {
      if (rule.type === 'atrule' || rule.parent.type === 'atrule') { return; }
    }

    rule.eachDecl(function (decl, i) {
      var value = decl.value;

      if (value.indexOf('rem') !== -1) {

        var prop = vendor.unprefixed(decl.prop);
        // replace rems only if needed
        if (!(_VALUES.test(value) || _PROPS.test(prop))) {

          value = value.replace(_remgex, function ($1) {
            // Round decimal pixels down to match webkit and opera behavior:
            // http://tylertate.com/blog/2012/01/05/subpixel-rounding.html
            return Math.floor(parseFloat($1) * toPx(_rootvalue)) + 'px';
          });

          if (_options.replace) {
            decl.value = value;
          } else {
            rule.insertBefore(i, decl.clone({ value: value }));
          }

        }
      }
    });

  });

};

// Return a unitless pixel value from any root font-size value.
function toPx (value) {
  var parts = /^(\d+\.?\d*)([a-zA-Z%]*)$/.exec(value);
  var number = parts[1];
  var unit = parts[2];

  if (unit === 'px' || unit === '') {
    return parseFloat(number);
  }
  else if (unit === 'em' || unit === 'rem') {
    return parseFloat(number) * 16;
  }
  else if (unit === '%') {
    return (parseFloat(number) / 100) * 16;
  }

  // TODO: Should we throw an error here?
  return false;
}

var pixrem = function (rootvalue, options) {
  return new Pixrem(rootvalue, options);
};
pixrem.process = function (css, rootvalue, options, postcssoptions) {
  return new Pixrem(rootvalue, options).process(css, postcssoptions);
};
pixrem.postcss = function (css) {
  return new Pixrem().postcss(css);
};

module.exports = pixrem;
<|endoftext|>


<commit_before>var fs = require('fs');
var exec = require('child_process').exec;

var dbPath = './db.json';
var pidPath = './vibes.pid';

// if pid exists then delete
if (fs.existsSync(pidPath)) {
  fs.unlinkSync(pidPath);
}

var Player = function() {

  var self = this;

  /**
   * Play
   * Create database list and play song from file
   */
  self.play = function() {
    if (fs.existsSync(pidPath)) {
      console.log('Ignore request');
    }
    else {
      var list = fs.readdirSync(process.env.LOCAL_DIRECTORY);

      var db = JSON.parse(fs.readFileSync(dbPath));

      // create database if empty
      if (db.length === 0) {
        if (list.length > 0) {
          var store = [];
          list.forEach(function(file) {
            store.push(file);
          });

          fs.writeFileSync(dbPath, JSON.stringify(store), 'utf8');
        }
        // reload database
        db = JSON.parse(fs.readFileSync(dbPath));
      }

      var selectedFile = db[Math.floor(Math.random()*db.length)];

      var index = db.indexOf(selectedFile);
      db.splice(index, 1);
      fs.writeFileSync(dbPath, JSON.stringify(db), 'utf8');

      var play = 'omxplayer ' + process.env.LOCAL_DIRECTORY + selectedFile;

      var child = exec(play, function(err, stdout, stderr) {
          if (err) throw err;
          console.log('Play: ' + selectedFile);
      });

      // save pid file
      fs.writeFileSync(pidPath, child.pid, 'utf8');

      // listener close
      child.on('close', function(code) {
          // remove pid file
          fs.unlinkSync(pidPath);

          // next file
          self.play();
      });
    }
  };

  /**
   * Stop
   * Stop player
   */
   self.stop = function() {
     if (fs.existsSync(pidPath)) {
       var command = 'ps -ef | grep omxplayer | grep -v grep | awk \'{print $2}\' | xargs kill -9';
       var child = exec(command, function(err, stdout, stderr) {
         if (err) throw err;
         console.log('Stopping...');
       });

       child.stdout.on('data', function(data) {
           console.log('stdout: ' + data);
       });

       child.stderr.on('data', function(data) {
           console.log('stdout: ' + data);
       });

       child.on('close', function(code) {
         console.log('Stoped ✓');
         fs.unlinkSync(pidPath);
       });
     }
     else {
       console.log(pidPath + 'don\'t exists.')
     }
   }
};

module.exports = new Player();
<commit_msg>remove 9 from command<commit_after>var fs = require('fs');
var exec = require('child_process').exec;

var dbPath = './db.json';
var pidPath = './vibes.pid';

// if pid exists then delete
if (fs.existsSync(pidPath)) {
  fs.unlinkSync(pidPath);
}

var Player = function() {

  var self = this;

  /**
   * Play
   * Create database list and play song from file
   */
  self.play = function() {
    if (fs.existsSync(pidPath)) {
      console.log('Ignore request');
    }
    else {
      var list = fs.readdirSync(process.env.LOCAL_DIRECTORY);

      var db = JSON.parse(fs.readFileSync(dbPath));

      // create database if empty
      if (db.length === 0) {
        if (list.length > 0) {
          var store = [];
          list.forEach(function(file) {
            store.push(file);
          });

          fs.writeFileSync(dbPath, JSON.stringify(store), 'utf8');
        }
        // reload database
        db = JSON.parse(fs.readFileSync(dbPath));
      }

      var selectedFile = db[Math.floor(Math.random()*db.length)];

      var index = db.indexOf(selectedFile);
      db.splice(index, 1);
      fs.writeFileSync(dbPath, JSON.stringify(db), 'utf8');

      var play = 'omxplayer ' + process.env.LOCAL_DIRECTORY + selectedFile;

      var child = exec(play, function(err, stdout, stderr) {
          if (err) throw err;
          console.log('Play: ' + selectedFile);
      });

      // save pid file
      fs.writeFileSync(pidPath, child.pid, 'utf8');

      // listener close
      child.on('close', function(code) {
          // remove pid file
          fs.unlinkSync(pidPath);

          // next file
          self.play();
      });
    }
  };

  /**
   * Stop
   * Stop player
   */
   self.stop = function() {
     if (fs.existsSync(pidPath)) {
       var command = 'ps -ef | grep omxplayer | grep -v grep | awk \'{print $2}\' | xargs kill';
       var child = exec(command, function(err, stdout, stderr) {
         if (err) throw err;
         console.log('Stopping...');
       });

       child.stdout.on('data', function(data) {
           console.log('stdout: ' + data);
       });

       child.stderr.on('data', function(data) {
           console.log('stdout: ' + data);
       });

       child.on('close', function(code) {
         console.log('Stoped ✓');
         fs.unlinkSync(pidPath);
       });
     }
     else {
       console.log(pidPath + 'don\'t exists.')
     }
   }
};

module.exports = new Player();
<|endoftext|>


<commit_before>var _ = require('lodash');
var Q = require('q');
var semver = require('semver');
var path = require('path');
var url = require('url');
var fs = require('./utils/fs');
var resolve = require('resolve');

var pkg = require('../package.json');

var Plugin = function(book, name) {
    this.book = book;
    this.name = name;
    this.packageInfos = {};
    this.infos = {};

    // Bind methods
    _.bindAll(this);

    _.each([
        'gitbook-plugin-'+name,
        'gitbook-'+name,
        name,
    ], function(_name) {
        // Load from the book
        if (this.load(_name, book.root)) return false;

        // Load from default plugins
        if (this.load(_name, __dirname)) return false;
    }, this);
};

// Type of plugins resources
Plugin.RESOURCES = ['js', 'css'];
Plugin.HOOKS = [
    'init', 'finish', 'finish:before', 'config', 'page', 'page:before'
];

// Load from a name
Plugin.prototype.load = function(name, baseDir) {
    try {
        var res = resolve.sync(name+'/package.json', { basedir: baseDir });

        this.baseDir = path.dirname(res);
        this.packageInfos = require(res);
        this.infos = require(resolve.sync(name, { basedir: baseDir }));
        this.name = name;

        return true;
    } catch (e) {
        this.packageInfos = {};
        this.infos = {};
        return false;
    }
};

Plugin.prototype.normalizeResource = function(resource) {
    // Parse the resource path
    var parsed = url.parse(resource);

    // This is a remote resource
    // so we will simply link to using it's URL
    if (parsed.protocol) {
        return {
            'url': resource
        };
    }

    // This will be copied over from disk
    // and shipped with the book's build
    return { 'path': this.name+'/'+resource };
};

// Return resources
Plugin.prototype._getResources = function(base) {
    base = base;
    var book = this.infos[base];

    // Compatibility with version 1.x.x
    if (base == 'website') book = book || this.infos.book;

    // Nothing specified, fallback to default
    if (!book) {
        return Q({});
    }

    // Dynamic function
    if(typeof book === 'function') {
        // Call giving it the context of our book
        return Q().then(book.bind(this.book));
    }

    // Plain data object
    return Q(_.cloneDeep(book));
};

// Normalize resources and return them
Plugin.prototype.getResources = function(base) {
    var that = this;

    return this._getResources(base)
    .then(function(resources) {

        _.each(Plugin.RESOURCES, function(resourceType) {
            resources[resourceType] = (resources[resourceType] || []).map(that.normalizeResource);
        });

        return resources;
    });
};

// Normalize filters and return them
Plugin.prototype.getFilters = function() {
    return this.infos.filters || {};
};

// Normalize blocks and return them
Plugin.prototype.getBlocks = function() {
    return this.infos.blocks || {};
};

// Test if it's a valid plugin
Plugin.prototype.isValid = function() {
    var that = this;
    var isValid = (
        this.packageInfos &&
        this.packageInfos.name &&
        this.packageInfos.engines &&
        this.packageInfos.engines.gitbook &&
        semver.satisfies(pkg.version, this.packageInfos.engines.gitbook)
    );

    // Valid hooks
    _.each(this.infos.hooks, function(hook, hookName) {
        if (_.contains(Plugin.HOOKS, hookName)) return;
        that.book.log.warn.ln('Hook ''+hookName+' 'used by plugin ''+that.packageInfos.name+'' has been removed or is deprecated');
    });

    return isValid;
};

// Resolve file path
Plugin.prototype.resolveFile = function(filename) {
    return path.resolve(this.baseDir, filename);
};

// Resolve file path
Plugin.prototype.callHook = function(name, data) {
    // Our book will be the context to apply
    var context = this.book;

    var hookFunc = this.infos.hooks? this.infos.hooks[name] : null;
    data = data || {};

    if (!hookFunc) return Q(data);

    this.book.log.debug.ln('call hook', name);
    if (!_.contains(Plugin.HOOKS, name)) this.book.log.warn.ln('hook ''+name+'' used by plugin ''+this.name+'' is deprecated, and will be removed in the coming versions');

    return Q()
    .then(function() {
        return hookFunc.apply(context, [data]);
    });
};

// Copy plugin assets fodler
Plugin.prototype.copyAssets = function(out, base) {
    var that = this;

    return this.getResources(base)
    .get('assets')
    .then(function(assets) {
        // Assets are undefined
        if(!assets) return false;

        return fs.copy(
            that.resolveFile(assets),
            out
        ).then(_.constant(true));
    }, _.constant(false));
};

module.exports = Plugin;
<commit_msg>Fix js error<commit_after>var _ = require('lodash');
var Q = require('q');
var semver = require('semver');
var path = require('path');
var url = require('url');
var fs = require('./utils/fs');
var resolve = require('resolve');

var pkg = require('../package.json');

var Plugin = function(book, name) {
    this.book = book;
    this.name = name;
    this.packageInfos = {};
    this.infos = {};

    // Bind methods
    _.bindAll(this);

    _.each([
        'gitbook-plugin-'+name,
        'gitbook-'+name,
        name,
    ], function(_name) {
        // Load from the book
        if (this.load(_name, book.root)) return false;

        // Load from default plugins
        if (this.load(_name, __dirname)) return false;
    }, this);
};

// Type of plugins resources
Plugin.RESOURCES = ['js', 'css'];
Plugin.HOOKS = [
    'init', 'finish', 'finish:before', 'config', 'page', 'page:before'
];

// Load from a name
Plugin.prototype.load = function(name, baseDir) {
    try {
        var res = resolve.sync(name+'/package.json', { basedir: baseDir });

        this.baseDir = path.dirname(res);
        this.packageInfos = require(res);
        this.infos = require(resolve.sync(name, { basedir: baseDir }));
        this.name = name;

        return true;
    } catch (e) {
        this.packageInfos = {};
        this.infos = {};
        return false;
    }
};

Plugin.prototype.normalizeResource = function(resource) {
    // Parse the resource path
    var parsed = url.parse(resource);

    // This is a remote resource
    // so we will simply link to using it's URL
    if (parsed.protocol) {
        return {
            'url': resource
        };
    }

    // This will be copied over from disk
    // and shipped with the book's build
    return { 'path': this.name+'/'+resource };
};

// Return resources
Plugin.prototype._getResources = function(base) {
    base = base;
    var book = this.infos[base];

    // Compatibility with version 1.x.x
    if (base == 'website') book = book || this.infos.book;

    // Nothing specified, fallback to default
    if (!book) {
        return Q({});
    }

    // Dynamic function
    if(typeof book === 'function') {
        // Call giving it the context of our book
        return Q().then(book.bind(this.book));
    }

    // Plain data object
    return Q(_.cloneDeep(book));
};

// Normalize resources and return them
Plugin.prototype.getResources = function(base) {
    var that = this;

    return this._getResources(base)
    .then(function(resources) {

        _.each(Plugin.RESOURCES, function(resourceType) {
            resources[resourceType] = (resources[resourceType] || []).map(that.normalizeResource);
        });

        return resources;
    });
};

// Normalize filters and return them
Plugin.prototype.getFilters = function() {
    return this.infos.filters || {};
};

// Normalize blocks and return them
Plugin.prototype.getBlocks = function() {
    return this.infos.blocks || {};
};

// Test if it's a valid plugin
Plugin.prototype.isValid = function() {
    var that = this;
    var isValid = (
        this.packageInfos &&
        this.packageInfos.name &&
        this.packageInfos.engines &&
        this.packageInfos.engines.gitbook &&
        semver.satisfies(pkg.version, this.packageInfos.engines.gitbook)
    );

    // Valid hooks
    _.each(this.infos.hooks, function(hook, hookName) {
        if (_.contains(Plugin.HOOKS, hookName)) return;
        that.book.log.warn.ln('Hook "'+hookName+'"" used by plugin "'+that.packageInfos.name+'" has been removed or is deprecated');
    });

    return isValid;
};

// Resolve file path
Plugin.prototype.resolveFile = function(filename) {
    return path.resolve(this.baseDir, filename);
};

// Resolve file path
Plugin.prototype.callHook = function(name, data) {
    // Our book will be the context to apply
    var context = this.book;

    var hookFunc = this.infos.hooks? this.infos.hooks[name] : null;
    data = data || {};

    if (!hookFunc) return Q(data);

    this.book.log.debug.ln('call hook', name);
    if (!_.contains(Plugin.HOOKS, name)) this.book.log.warn.ln('hook "'+name+'" used by plugin "'+this.name+'" is deprecated, and will be removed in the coming versions');

    return Q()
    .then(function() {
        return hookFunc.apply(context, [data]);
    });
};

// Copy plugin assets fodler
Plugin.prototype.copyAssets = function(out, base) {
    var that = this;

    return this.getResources(base)
    .get('assets')
    .then(function(assets) {
        // Assets are undefined
        if(!assets) return false;

        return fs.copy(
            that.resolveFile(assets),
            out
        ).then(_.constant(true));
    }, _.constant(false));
};

module.exports = Plugin;
<|endoftext|>


<commit_before>var path = require('path');
var fse = require('fs-extra');
var _ = require('lodash');
var mutexify = require('mutexify');

var lock = mutexify();

function ManifestPlugin(opts) {
  this.opts = _.assign({
    basePath: '',
    fileName: 'manifest.json',
    transformExtensions: /^(gz|map)$/i,
    writeToFileEmit: false,
    seed: null,
    filter: null,
    map: null,
    generate: null,
  }, opts || {});
}

ManifestPlugin.prototype.getFileType = function(str) {
  str = str.replace(/\?.*/, '');
  var split = str.split('.');
  var ext = split.pop();
  if (this.opts.transformExtensions.test(ext)) {
    ext = split.pop() + '.' + ext;
  }
  return ext;
};

ManifestPlugin.prototype.apply = function(compiler) {
  var seed = this.opts.seed || {};
  var moduleAssets = {};

  compiler.plugin("compilation", function (compilation) {
    compilation.plugin('module-asset', function (module, file) {
      moduleAssets[file] = path.join(
          path.dirname(file),
          path.basename(module.userRequest)
      );
    });
  });

  compiler.plugin('emit', function(compilation, compileCallback) {
    var publicPath = compilation.options.output.publicPath;
    var stats = compilation.getStats().toJson();

    var files = compilation.chunks.reduce(function(files, chunk) {
      return chunk.files.reduce(function (files, path) {
        var name = chunk.name ? chunk.name : null;

        if (name) {
          name = name + '.' + this.getFileType(path);
        } else {
          // For nameless chunks, just map the files directly.
          name = path;
        }

        return files.concat({
          path: path,
          chunk: chunk,
          name: name,
          isInitial: chunk.isInitial ? chunk.isInitial() : chunk.initial,
          isChunk: true,
          isAsset: false,
          isModuleAsset: false
        });
      }.bind(this), files);
    }.bind(this), []);

    // module assets don't show up in assetsByChunkName.
    // we're getting them this way;
    files = stats.assets.reduce(function (files, asset) {
      var name = moduleAssets[asset.name];
      if (name) {
        return files.concat({
          path: asset.name,
          name: name,
          isInitial: false,
          isChunk: false,
          isAsset: true,
          isModuleAsset: true
        });
      }

      var isEntryAsset = asset.chunks.length > 0;
      if (isEntryAsset) {
        return files;
      }

      return files.concat({
        path: asset.name,
        name: asset.name,
        isInitial: false,
        isChunk: false,
        isAsset: true,
        isModuleAsset: false
      });
    }, files);

    files = files.filter(function (file) {
      // Don't add hot updates to manifest
      return file.path.indexOf('hot-update') === -1;
    });

    // Append optional basepath onto all references.
    // This allows output path to be reflected in the manifest.
    if (this.opts.basePath) {
      files = files.map(function(file) {
        file.name = this.opts.basePath + file.name;
        return file;
      }.bind(this));
    }

    if (publicPath) {
      // Similar to basePath but only affects the value (similar to how
      // output.publicPath turns require('foo/bar') into '/public/foo/bar', see
      // https://github.com/webpack/docs/wiki/configuration#outputpublicpath
      files = files.map(function(file) {
        file.path = publicPath + file.path;
        return file;
      }.bind(this));
    }

    files = files.map(file => {
      file.name = file.name.replace(/\\/g, '/');
      file.path = file.path.replace(/\\/g, '/');
      return file;
    });

    if (this.opts.filter) {
      files = files.filter(this.opts.filter);
    }

    if (this.opts.map) {
      files = files.map(this.opts.map);
    }

    if (this.opts.sort) {
      files = files.sort(this.opts.sort);
    }

    var manifest;
    if (this.opts.generate) {
      manifest = this.opts.generate(seed, files);
    } else {
      manifest = files.reduce(function (manifest, file) {
        manifest[file.name] = file.path;
        return manifest;
      }, seed);
    }

    var json = JSON.stringify(manifest, null, 2);

    var outputFolder = compilation.options.output.path;
    var outputFile = path.resolve(compilation.options.output.path, this.opts.fileName);
    var outputName = path.relative(outputFolder, outputFile);

    compilation.assets[outputName] = {
      source: function() {
        return json;
      },
      size: function() {
        return json.length;
      }
    };

    if (this.opts.writeToFileEmit) {
      fse.outputFileSync(outputFile, json);
    }

    // NOTE: make sure webpack is not writing multiple manifests simultaneously
    lock(function(release) {
      compiler.plugin('after-emit', function(compilation, cb) {
        release();
        cb();
      });

      compilation.applyPluginsAsync('webpack-manifest-plugin-after-emit', manifest, compileCallback);
    });
  }.bind(this));
};

module.exports = ManifestPlugin;
<commit_msg>fix: default sort option (#95)<commit_after>var path = require('path');
var fse = require('fs-extra');
var _ = require('lodash');
var mutexify = require('mutexify');

var lock = mutexify();

function ManifestPlugin(opts) {
  this.opts = _.assign({
    basePath: '',
    fileName: 'manifest.json',
    transformExtensions: /^(gz|map)$/i,
    writeToFileEmit: false,
    seed: null,
    filter: null,
    map: null,
    generate: null,
    sort: null,
  }, opts || {});
}

ManifestPlugin.prototype.getFileType = function(str) {
  str = str.replace(/\?.*/, '');
  var split = str.split('.');
  var ext = split.pop();
  if (this.opts.transformExtensions.test(ext)) {
    ext = split.pop() + '.' + ext;
  }
  return ext;
};

ManifestPlugin.prototype.apply = function(compiler) {
  var seed = this.opts.seed || {};
  var moduleAssets = {};

  compiler.plugin("compilation", function (compilation) {
    compilation.plugin('module-asset', function (module, file) {
      moduleAssets[file] = path.join(
          path.dirname(file),
          path.basename(module.userRequest)
      );
    });
  });

  compiler.plugin('emit', function(compilation, compileCallback) {
    var publicPath = compilation.options.output.publicPath;
    var stats = compilation.getStats().toJson();

    var files = compilation.chunks.reduce(function(files, chunk) {
      return chunk.files.reduce(function (files, path) {
        var name = chunk.name ? chunk.name : null;

        if (name) {
          name = name + '.' + this.getFileType(path);
        } else {
          // For nameless chunks, just map the files directly.
          name = path;
        }

        return files.concat({
          path: path,
          chunk: chunk,
          name: name,
          isInitial: chunk.isInitial ? chunk.isInitial() : chunk.initial,
          isChunk: true,
          isAsset: false,
          isModuleAsset: false
        });
      }.bind(this), files);
    }.bind(this), []);

    // module assets don't show up in assetsByChunkName.
    // we're getting them this way;
    files = stats.assets.reduce(function (files, asset) {
      var name = moduleAssets[asset.name];
      if (name) {
        return files.concat({
          path: asset.name,
          name: name,
          isInitial: false,
          isChunk: false,
          isAsset: true,
          isModuleAsset: true
        });
      }

      var isEntryAsset = asset.chunks.length > 0;
      if (isEntryAsset) {
        return files;
      }

      return files.concat({
        path: asset.name,
        name: asset.name,
        isInitial: false,
        isChunk: false,
        isAsset: true,
        isModuleAsset: false
      });
    }, files);

    files = files.filter(function (file) {
      // Don't add hot updates to manifest
      return file.path.indexOf('hot-update') === -1;
    });

    // Append optional basepath onto all references.
    // This allows output path to be reflected in the manifest.
    if (this.opts.basePath) {
      files = files.map(function(file) {
        file.name = this.opts.basePath + file.name;
        return file;
      }.bind(this));
    }

    if (publicPath) {
      // Similar to basePath but only affects the value (similar to how
      // output.publicPath turns require('foo/bar') into '/public/foo/bar', see
      // https://github.com/webpack/docs/wiki/configuration#outputpublicpath
      files = files.map(function(file) {
        file.path = publicPath + file.path;
        return file;
      }.bind(this));
    }

    files = files.map(file => {
      file.name = file.name.replace(/\\/g, '/');
      file.path = file.path.replace(/\\/g, '/');
      return file;
    });

    if (this.opts.filter) {
      files = files.filter(this.opts.filter);
    }

    if (this.opts.map) {
      files = files.map(this.opts.map);
    }

    if (this.opts.sort) {
      files = files.sort(this.opts.sort);
    }

    var manifest;
    if (this.opts.generate) {
      manifest = this.opts.generate(seed, files);
    } else {
      manifest = files.reduce(function (manifest, file) {
        manifest[file.name] = file.path;
        return manifest;
      }, seed);
    }

    var json = JSON.stringify(manifest, null, 2);

    var outputFolder = compilation.options.output.path;
    var outputFile = path.resolve(compilation.options.output.path, this.opts.fileName);
    var outputName = path.relative(outputFolder, outputFile);

    compilation.assets[outputName] = {
      source: function() {
        return json;
      },
      size: function() {
        return json.length;
      }
    };

    if (this.opts.writeToFileEmit) {
      fse.outputFileSync(outputFile, json);
    }

    // NOTE: make sure webpack is not writing multiple manifests simultaneously
    lock(function(release) {
      compiler.plugin('after-emit', function(compilation, cb) {
        release();
        cb();
      });

      compilation.applyPluginsAsync('webpack-manifest-plugin-after-emit', manifest, compileCallback);
    });
  }.bind(this));
};

module.exports = ManifestPlugin;
<|endoftext|>


<commit_before>var _ = require('underscore');
const corePlugins = [
    'styles-output', 'scripts-output', 'static-output',
    'scope', 'router', 'template', 'inline-styles', 'stylus', 'module-map', 'package-config', 'update-externals',
    'inline-styles-resources', 'styles', 'scripts', 'static'];
var fileUtils = require("./fileUtil");

var globalPlugins = {};

exports.plugin = function(name, plugin) {
  globalPlugins[name] = plugin;
  plugin.id = name;
};

exports.plugin('module-map', require('./plugins/module-map'));
exports.plugin('package-config', require('./plugins/package-config'));
exports.plugin('router', require('./plugins/router'));
exports.plugin('scope', require('./plugins/scope'));
exports.plugin('stylus', require('./plugins/stylus'));
exports.plugin('inline-styles', require('./plugins/inline-styles'));
exports.plugin('inline-styles-resources', require('./plugins/inline-styles-resources'));
exports.plugin('update-externals', require('./plugins/update-externals'));
exports.plugin('template', require('./plugins/template'));
exports.plugin('styles', require('./plugins/styles.js'));
exports.plugin('scripts', require('./plugins/scripts.js'));
exports.plugin('static', require('./plugins/static.js'));
exports.plugin('styles-output', require('./plugins/styles-output.js'));
exports.plugin('scripts-output', require('./plugins/scripts-output.js'));
exports.plugin('static-output', require('./plugins/static-output.js'));

exports.create = function(options) {
  var plugins;
  var modes; // all registered modes
  var pluginModes; // map of modes and plugins scoped to the mode
  var modeAll; // plugins that are scoped to all modes

  function runPlugins(context, methodName, complete, failOver) {
    var len = 0;
    return (function next(complete) {
      var plugin = plugins[len];
      len++;
      if (plugin) {
        // if plugin shouldn't work with current mode, go to next
        if ((pluginModes[context.mode].indexOf(plugin) < 0) && modeAll.indexOf(plugin) < 0) {
          return next(complete);
        }

        var method = plugin[methodName];
        if (method) {
          return method.call(plugin, context, next, complete);
        } else {
          return next(complete);
        }
      } else {
        if (complete) {
          // async
          complete(undefined, failOver && failOver());
        } else {
          // sync
          return failOver && failOver();
        }
      }
    })(complete);
  }

  function registerPlugin(plugin) {
    var _plugin = globalPlugins[plugin] || plugin;

    var mode = _plugin.mode;
    if (mode) {
      if (_.isString(mode)) {
        mode = [mode];
      }
      _.each(mode, function(_mode) {
        if (mode === 'all') {
          // allow plugins to contribute new modes and participate in all modes
          modeAll.push(_plugin);
        } else {
          if (modes.indexOf(_mode) < 0) {
            modes.push(_mode);
            pluginModes[_mode] = [];
          }
          pluginModes[_mode].push(_plugin);
        }
      });
    } else {
      modeAll.push(_plugin);
    }
    plugins.push(_plugin);
    plugins.sort(function(a, b) {
      return (a.priority || 50) - (b.priority || 50);
    });
  }

  return {
    use: function(plugin) {
      if (plugin.path) {
        var path = plugin.path;
        var options = plugin.options;
        try {
          plugin = require(path);
        } catch (e) {
          // no global resolved, try and load plugin relative to the project
          path = fileUtils.resolvePath(path);

          var relativePattern = /^[^/]/;
          if (path.match(relativePattern)) {
            path = process.cwd() + '/' + path;
          }
          plugin = require(path);
        }
        if ('function' === typeof plugin) {
          plugin = plugin(options);
        }
      }
      registerPlugin(plugin);
    },

    initialize: function(config) {
      // reset
      plugins = [];
      modes = []; // all registered modes
      pluginModes = {}; // map of modes and plugins scoped to the mode
      modeAll = []; // plugins that are scoped to all modes

      // load the core plugins
      if (!options.ignoreCorePlugins) {
        corePlugins.forEach(registerPlugin);
      }

      var self = this;
      function plugin(plugins) {
        if (plugins) {
          plugins.forEach(self.use, self);
        }
      }

      // load command line plugins
      plugin(options.plugins);

      // load lumbar.json plugins
      plugin(config.attributes.plugins);
    },

    outputConfigs: function(context, complete) {
      runPlugins(context, 'outputConfigs', complete, function() {
        // Default to a one to one mapping for a given {platform, package, module, mode} combo
        return [ {} ];
      });
    },
    modeComplete: function(context, complete) {
      runPlugins(context, 'modeComplete', complete);
    },
    fileName: function(context, complete) {
      runPlugins(context, 'fileName', complete);
    },

    fileFilter: function(context) {
      return runPlugins(context, 'fileFilter');
    },
    moduleResources: function(context, complete) {
      runPlugins(context, 'moduleResources', complete, function() {
        var module = context.module;
        return (module[context.mode] || []).slice();
      });
    },
    resourceList: function(context, complete) {
      runPlugins(context, 'resourceList', complete, function() { return [context.resource]; });
    },

    file: function(context, complete) {
      runPlugins(context, 'file', complete);
    },
    module: function(context, complete) {
      runPlugins(context, 'module', complete);
    },
    resource: function(context, complete) {
      runPlugins(context, 'resource', complete, function() { return context.resource; });
    },
    modes: function() {
      return modes;
    }
  };
};
<commit_msg>Plugins.get implementation<commit_after>var _ = require('underscore');
const corePlugins = [
    'styles-output', 'scripts-output', 'static-output',
    'scope', 'router', 'template', 'inline-styles', 'stylus', 'module-map', 'package-config', 'update-externals',
    'inline-styles-resources', 'styles', 'scripts', 'static'];
var fileUtils = require("./fileUtil");

var globalPlugins = {};

exports.plugin = function(name, plugin) {
  globalPlugins[name] = plugin;
  plugin.id = name;
};

exports.plugin('module-map', require('./plugins/module-map'));
exports.plugin('package-config', require('./plugins/package-config'));
exports.plugin('router', require('./plugins/router'));
exports.plugin('scope', require('./plugins/scope'));
exports.plugin('stylus', require('./plugins/stylus'));
exports.plugin('inline-styles', require('./plugins/inline-styles'));
exports.plugin('inline-styles-resources', require('./plugins/inline-styles-resources'));
exports.plugin('update-externals', require('./plugins/update-externals'));
exports.plugin('template', require('./plugins/template'));
exports.plugin('styles', require('./plugins/styles.js'));
exports.plugin('scripts', require('./plugins/scripts.js'));
exports.plugin('static', require('./plugins/static.js'));
exports.plugin('styles-output', require('./plugins/styles-output.js'));
exports.plugin('scripts-output', require('./plugins/scripts-output.js'));
exports.plugin('static-output', require('./plugins/static-output.js'));

exports.create = function(options) {
  var plugins;
  var modes; // all registered modes
  var pluginModes; // map of modes and plugins scoped to the mode
  var modeAll; // plugins that are scoped to all modes

  function runPlugins(context, methodName, complete, failOver) {
    var len = 0;
    return (function next(complete) {
      var plugin = plugins[len];
      len++;
      if (plugin) {
        // if plugin shouldn't work with current mode, go to next
        if ((pluginModes[context.mode].indexOf(plugin) < 0) && modeAll.indexOf(plugin) < 0) {
          return next(complete);
        }

        var method = plugin[methodName];
        if (method) {
          return method.call(plugin, context, next, complete);
        } else {
          return next(complete);
        }
      } else {
        if (complete) {
          // async
          complete(undefined, failOver && failOver());
        } else {
          // sync
          return failOver && failOver();
        }
      }
    })(complete);
  }

  function registerPlugin(plugin) {
    var _plugin = globalPlugins[plugin] || plugin;

    var mode = _plugin.mode;
    if (mode) {
      if (_.isString(mode)) {
        mode = [mode];
      }
      _.each(mode, function(_mode) {
        if (mode === 'all') {
          // allow plugins to contribute new modes and participate in all modes
          modeAll.push(_plugin);
        } else {
          if (modes.indexOf(_mode) < 0) {
            modes.push(_mode);
            pluginModes[_mode] = [];
          }
          pluginModes[_mode].push(_plugin);
        }
      });
    } else {
      modeAll.push(_plugin);
    }
    plugins.push(_plugin);
    plugins.sort(function(a, b) {
      return (a.priority || 50) - (b.priority || 50);
    });
  }

  return {
    get: function(name) {
      return plugins.reduce(function(plugin, left) {
        return plugin.id === name ? plugin : left;
      });
    },
    use: function(plugin) {
      if (plugin.path) {
        var path = plugin.path;
        var options = plugin.options;
        try {
          plugin = require(path);
        } catch (e) {
          // no global resolved, try and load plugin relative to the project
          path = fileUtils.resolvePath(path);

          var relativePattern = /^[^/]/;
          if (path.match(relativePattern)) {
            path = process.cwd() + '/' + path;
          }
          plugin = require(path);
        }
        if ('function' === typeof plugin) {
          plugin = plugin(options);
        }
      }
      registerPlugin(plugin);
    },

    initialize: function(config) {
      // reset
      plugins = [];
      modes = []; // all registered modes
      pluginModes = {}; // map of modes and plugins scoped to the mode
      modeAll = []; // plugins that are scoped to all modes

      // load the core plugins
      if (!options.ignoreCorePlugins) {
        corePlugins.forEach(registerPlugin);
      }

      var self = this;
      function plugin(plugins) {
        if (plugins) {
          plugins.forEach(self.use, self);
        }
      }

      // load command line plugins
      plugin(options.plugins);

      // load lumbar.json plugins
      plugin(config.attributes.plugins);
    },

    outputConfigs: function(context, complete) {
      runPlugins(context, 'outputConfigs', complete, function() {
        // Default to a one to one mapping for a given {platform, package, module, mode} combo
        return [ {} ];
      });
    },
    modeComplete: function(context, complete) {
      runPlugins(context, 'modeComplete', complete);
    },
    fileName: function(context, complete) {
      runPlugins(context, 'fileName', complete);
    },

    fileFilter: function(context) {
      return runPlugins(context, 'fileFilter');
    },
    moduleResources: function(context, complete) {
      runPlugins(context, 'moduleResources', complete, function() {
        var module = context.module;
        return (module[context.mode] || []).slice();
      });
    },
    resourceList: function(context, complete) {
      runPlugins(context, 'resourceList', complete, function() { return [context.resource]; });
    },

    file: function(context, complete) {
      runPlugins(context, 'file', complete);
    },
    module: function(context, complete) {
      runPlugins(context, 'module', complete);
    },
    resource: function(context, complete) {
      runPlugins(context, 'resource', complete, function() { return context.resource; });
    },
    modes: function() {
      return modes;
    }
  };
};
<|endoftext|>