<commit_before>/*!
 * Copyright (C) 2017 Glayzzle (BSD3 License)
 * @authors https://github.com/glayzzle/php-writer/graphs/contributors
 * @url http://glayzzle.com/php-writer
 */
'use strict';

var parser = require('php-parser');
var unparser = require('php-unparser');
var editor = require('./helpers/editor');

var Namespace = require('./namespace');
var Class = require('./class');
var fn = require('./function');
var Interface = require('./interface');
var Trait = require('./trait');

// Parser default options
var defaultOptions = {
  parser: {
    extractDoc: true
  }
};

/**
 * @varructor
 */
var Writer = function(buffer, options = {}) {
  options = Object.assign({}, defaultOptions, options);
  this.ast = parser.parseCode(buffer, options);
};
editor(Writer, 1);

/**
 * Finds a namespace
 * @param {String} name
 * @return {Namespace|Null}
 */
Writer.prototype.findNamespace = function(name) {
  return Namespace.locate(this.ast.children, name);
};

/**
 * Locates the object namespace
 * @param {String} name
 * @return {Namespace|Null}
 */
Writer.prototype.nsLocator = function(name) {
  name = name.trim('\\').split('\\');
  if (name.length > 1) {
    var cName = name.pop();
    return [cName, this.findNamespace(name.join('\\'))];
  } else {
    return [name[0], this.findNamespace('')];
  }
};

/**
 * Finds a class
 * @param {String} name
 * @return {Class|Null}
 */
Writer.prototype.findClass = function(name) {
  var ns = this.nsLocator(name);
  if (ns[1]) return ns[1].findClass(ns[0]);
  return Class.locate(this.ast.children, ns[0]);
};

/**
 * Finds a function
 * @param {String} name
 * @return {Function|Null}
 */
Writer.prototype.findFunction = function(name) {
  var ns = this.nsLocator(name);
  if (ns[1]) return ns[1].findFunction(ns[0]);
  return fn.locate(this.ast.children, ns[0]);
};

/**
 * @param {String} name
 * @return {Trait|Null}
 */
Writer.prototype.findTrait = function(name) {
  var ns = this.nsLocator(name);
  if (ns[1]) return ns[1].findTrait(ns[0]);
  return Trait.locate(this.ast.children, ns[0]);
};

/**
 * @param {String} name
 * @return {Interface|Null}
 */
Writer.prototype.findInterface = function(name) {
  var ns = this.nsLocator(name);
  if (ns[1]) return ns[1].findInterface(ns[0]);
  return Interface.locate(this.ast.children, ns[0]);
};

/**
 * Convert back AST to php code
 * @return {String}
 */
Writer.prototype.toString = function() {
  return unparser(this.ast, {
    forceNamespaceBrackets: true,
    shortArray: false
  });
};

module.exports = Writer;
<commit_msg>Added default writer options<commit_after>/*!
 * Copyright (C) 2017 Glayzzle (BSD3 License)
 * @authors https://github.com/glayzzle/php-writer/graphs/contributors
 * @url http://glayzzle.com/php-writer
 */
'use strict';

var parser = require('php-parser');
var unparser = require('php-unparser');
var editor = require('./helpers/editor');

var Namespace = require('./namespace');
var Class = require('./class');
var fn = require('./function');
var Interface = require('./interface');
var Trait = require('./trait');

// Parser default options
var defaultOptions = {
  writer: {
    indent: true,
    dontUseWhitespaces: false,
    shortArray: true,
    forceNamespaceBrackets: false,
    bracketsNewLine: true
  },
  parser: {
    debug: false,
    locations: false,
    extractDoc: true,
    suppressErrors: false
  },
  lexer: {
    all_tokens: false,
    comment_tokens: false,
    mode_eval: false,
    asp_tags: false,
    short_tags: false
  },
  ast: {
    withPositions: true
  }
};

/**
 * @varructor
 */
var Writer = function(buffer, options = {}) {
  options = Object.assign({}, defaultOptions, options);
  this.ast = parser.parseCode(buffer, options);
};
editor(Writer, 1);

/**
 * Finds a namespace
 * @param {String} name
 * @return {Namespace|Null}
 */
Writer.prototype.findNamespace = function(name) {
  return Namespace.locate(this.ast.children, name);
};

/**
 * Locates the object namespace
 * @param {String} name
 * @return {Namespace|Null}
 */
Writer.prototype.nsLocator = function(name) {
  name = name.trim('\\').split('\\');
  if (name.length > 1) {
    var cName = name.pop();
    return [cName, this.findNamespace(name.join('\\'))];
  } else {
    return [name[0], this.findNamespace('')];
  }
};

/**
 * Finds a class
 * @param {String} name
 * @return {Class|Null}
 */
Writer.prototype.findClass = function(name) {
  var ns = this.nsLocator(name);
  if (ns[1]) return ns[1].findClass(ns[0]);
  return Class.locate(this.ast.children, ns[0]);
};

/**
 * Finds a function
 * @param {String} name
 * @return {Function|Null}
 */
Writer.prototype.findFunction = function(name) {
  var ns = this.nsLocator(name);
  if (ns[1]) return ns[1].findFunction(ns[0]);
  return fn.locate(this.ast.children, ns[0]);
};

/**
 * @param {String} name
 * @return {Trait|Null}
 */
Writer.prototype.findTrait = function(name) {
  var ns = this.nsLocator(name);
  if (ns[1]) return ns[1].findTrait(ns[0]);
  return Trait.locate(this.ast.children, ns[0]);
};

/**
 * @param {String} name
 * @return {Interface|Null}
 */
Writer.prototype.findInterface = function(name) {
  var ns = this.nsLocator(name);
  if (ns[1]) return ns[1].findInterface(ns[0]);
  return Interface.locate(this.ast.children, ns[0]);
};

/**
 * Convert back AST to php code
 * @return {String}
 */
Writer.prototype.toString = function() {
  return unparser(this.ast, {
    forceNamespaceBrackets: true,
    shortArray: false
  });
};

module.exports = Writer;
<|endoftext|>


<commit_before>import Alert from './components/Alert';
import Badge from './components/Badge';
import Breadcrumb from './components/Breadcrumb';
import BreadcrumbItem from './components/BreadcrumbItem';
import Button from './components/Button';
import ButtonGroup from './components/ButtonGroup';
import Card from './components/Card';
import Column from './components/Column';
import Container from './components/Container';
import Layout from './components/Layout';
import LayoutAside from './components/LayoutAside';
import LayoutContent from './components/LayoutContent';
import LayoutFooter from './components/LayoutFooter';
import LayoutHeader from './components/LayoutHeader';
import Row from './components/Row';

import Checkbox from './components/Checkbox';
import CheckboxButton from './components/CheckboxButton';
import CheckboxGroup from './components/CheckboxGroup';
import CheckboxButtonGroup from './components/CheckboxButtonGroup';
import Input from './components/Input';
import InputGroup from './components/InputGroup';
import InputNumber from './components/InputNumber';
import Radio from './components/Radio';
import RadioButton from './components/RadioButton';
import RadioGroup from './components/RadioGroup';
import RadioButtonGroup from './components/RadioButtonGroup';
import Textarea from './components/Textarea';

class Inkline {
    static components = [
        Alert,
        Badge,
        Breadcrumb,
        BreadcrumbItem,
        Button,
        ButtonGroup,
        Card,
        Column,
        Container,
        Layout,
        LayoutAside,
        LayoutContent,
        LayoutFooter,
        LayoutHeader,
        Row,

        Checkbox,
        CheckboxButton,
        CheckboxGroup,
        CheckboxButtonGroup,
        Input,
        InputGroup,
        InputNumber,
        Radio,
        RadioButton,
        RadioGroup,
        RadioButtonGroup,
        Textarea
    ];

    constructor () {
        if (typeof window !== 'undefined' && window.Vue) {
            this.install(window.Vue);
        }
    }

    static install (Vue) {
        this.components.map(component => {
            Vue.component(component.name, component);
        });
    }
}

export {
    Alert as IAlert,
    Badge as IBadge,
    Breadcrumb as IBreadcrumb,
    BreadcrumbItem as IBreadcrumbItem,
    Button as IButton,
    ButtonGroup as IButtonGroup,
    Card as ICard,
    Column as IColumn,
    Container as IContainer,
    Layout as ILayout,
    LayoutAside as ILayoutAside,
    LayoutContent as ILayoutContent,
    LayoutFooter as ILayoutFooter,
    LayoutHeader as ILayoutHeader,
    Row as IRow,

    Checkbox as ICheckbox,
    CheckboxButton as ICheckboxButton,
    CheckboxGroup as ICheckboxGroup,
    CheckboxButtonGroup as ICheckboxButtonGroup,
    Input as IInput,
    InputGroup as IInputGroup,
    InputNumber as IInputNumber,
    Radio as IRadio,
    RadioButton as IRadioButton,
    RadioGroup as IRadioGroup,
    RadioButtonGroup as IRadioButtonGroup,
    Textarea as ITextarea,
    Inkline
};

export default Inkline;<commit_msg>Added components to index.<commit_after>import Alert from './components/Alert';
import Badge from './components/Badge';
import Breadcrumb from './components/Breadcrumb';
import BreadcrumbItem from './components/BreadcrumbItem';
import Button from './components/Button';
import ButtonGroup from './components/ButtonGroup';
import Card from './components/Card';
import Collapsible from './components/Collapsible';
import CollapsibleItem from './components/CollapsibleItem';
import Column from './components/Column';
import Container from './components/Container';
import Layout from './components/Layout';
import LayoutAside from './components/LayoutAside';
import LayoutContent from './components/LayoutContent';
import LayoutFooter from './components/LayoutFooter';
import LayoutHeader from './components/LayoutHeader';
import Row from './components/Row';

import Checkbox from './components/Checkbox';
import CheckboxButton from './components/CheckboxButton';
import CheckboxGroup from './components/CheckboxGroup';
import CheckboxButtonGroup from './components/CheckboxButtonGroup';
import Input from './components/Input';
import InputGroup from './components/InputGroup';
import InputNumber from './components/InputNumber';
import Radio from './components/Radio';
import RadioButton from './components/RadioButton';
import RadioGroup from './components/RadioGroup';
import RadioButtonGroup from './components/RadioButtonGroup';
import Textarea from './components/Textarea';

class Inkline {
    static components = [
        Alert,
        Badge,
        Breadcrumb,
        BreadcrumbItem,
        Button,
        ButtonGroup,
        Card,
        Collapsible,
        CollapsibleItem,
        Column,
        Container,
        Layout,
        LayoutAside,
        LayoutContent,
        LayoutFooter,
        LayoutHeader,
        Row,

        Checkbox,
        CheckboxButton,
        CheckboxGroup,
        CheckboxButtonGroup,
        Input,
        InputGroup,
        InputNumber,
        Radio,
        RadioButton,
        RadioGroup,
        RadioButtonGroup,
        Textarea
    ];

    constructor () {
        if (typeof window !== 'undefined' && window.Vue) {
            this.install(window.Vue);
        }
    }

    static install (Vue) {
        this.components.map(component => {
            Vue.component(component.name, component);
        });
    }
}

export {
    Alert as IAlert,
    Badge as IBadge,
    Breadcrumb as IBreadcrumb,
    BreadcrumbItem as IBreadcrumbItem,
    Button as IButton,
    ButtonGroup as IButtonGroup,
    Card as ICard,
    Collapsible as ICollapsible,
    CollapsibleItem as ICollapsibleItem,
    Column as IColumn,
    Container as IContainer,
    Layout as ILayout,
    LayoutAside as ILayoutAside,
    LayoutContent as ILayoutContent,
    LayoutFooter as ILayoutFooter,
    LayoutHeader as ILayoutHeader,
    Row as IRow,

    Checkbox as ICheckbox,
    CheckboxButton as ICheckboxButton,
    CheckboxGroup as ICheckboxGroup,
    CheckboxButtonGroup as ICheckboxButtonGroup,
    Input as IInput,
    InputGroup as IInputGroup,
    InputNumber as IInputNumber,
    Radio as IRadio,
    RadioButton as IRadioButton,
    RadioGroup as IRadioGroup,
    RadioButtonGroup as IRadioButtonGroup,
    Textarea as ITextarea,
    Inkline
};

export default Inkline;<|endoftext|>


<commit_before>import { resolve, dirname, isAbsolute } from 'path';

// options resolvers
import * as requireHooksOptions from './options_resolvers';

// utils.
import { extractCssFile } from './utils';

const defaultOptions = {
    generateScopedName: '[name]__[local]___[hash:base64:5]'
};

export default function transformCssModules({ types: t }) {
    function resolveModulePath(filename) {
        const dir = dirname(filename);
        if (isAbsolute(dir)) return dir;
        if (process.env.PWD) return resolve(process.env.PWD, dir);
        return resolve(dir);
    }

    /**
     *
     * @param {String} filepath     javascript file path
     * @param {String} cssFile      requireed css file path
     * @returns {Array} array of class names
     */
    function requireCssFile(filepath, cssFile) {
        let filePathOrModuleName = cssFile;

        // only resolve path to file when we have a file path
        if (!/^\w/i.test(filePathOrModuleName)) {
            const from = resolveModulePath(filepath);
            filePathOrModuleName = resolve(from, filePathOrModuleName);
        }

        // css-modules-require-hooks throws if file is ignored
        try {
            return require(filePathOrModuleName);
        } catch (e) {
            // As a last resort, require the cssFile itself. This enables loading of CSS files from external deps
            try {
                return require(cssFile);
            } catch (e) {
                return {}; // return empty object, this simulates result of ignored stylesheet file
            }
        }
    }

    // is css modules require hook initialized?
    let initialized = false;
    // are we requiring a module for preprocessCss, processCss, etc?
    // we don't want them to be transformed using this plugin
    // because it will cause circular dependency in babel-node and babel-register process
    let inProcessingFunction = false;

    let matchExtensions = /\.css$/i;

    function matcher(extensions = ['.css']) {
        const extensionsPattern = extensions.join('|').replace(/\./g, '\\\.');
        return new RegExp(`(${extensionsPattern})$`, 'i');
    }

    function buildClassNameToScopeNameMap(tokens) {
        /* eslint-disable new-cap */
        return t.ObjectExpression(
            Object.keys(tokens).map(token =>
                t.ObjectProperty(
                    t.StringLiteral(token),
                    t.StringLiteral(tokens[token])
                )
            )
        );
    }

    const cssMap = new Map();
    let thisPluginOptions = null;

    const pluginApi = {
        manipulateOptions(options) {
            if (initialized || inProcessingFunction) {
                return options;
            }

            // find options for this plugin
            // we have to use this hack because plugin.key does not have to be 'css-modules-transform'
            // so we will identify it by comparing manipulateOptions
            thisPluginOptions = options.plugins.filter(
              ([plugin]) => plugin.manipulateOptions === pluginApi.manipulateOptions
            )[0][1];

            const currentConfig = { ...defaultOptions, ...thisPluginOptions };
            // this is not a css-require-ook config
            delete currentConfig.extractCss;

            // match file extensions, speeds up transform by creating one
            // RegExp ahead of execution time
            matchExtensions = matcher(currentConfig.extensions);

            const pushStylesCreator = (toWrap) => (css, filepath) => {
                let processed;

                if (typeof toWrap === 'function') {
                    processed = toWrap(css, filepath);
                }

                if (typeof processed !== 'string') processed = css;

                // set css content only if is new
                if (!cssMap.has(filepath) || cssMap.get(filepath) !== processed) {
                    cssMap.set(filepath, processed);
                }

                return processed;
            };

            // resolve options
            Object.keys(requireHooksOptions).forEach(key => {
                // skip undefined options
                if (currentConfig[key] === undefined) {
                    return;
                }

                inProcessingFunction = true;
                currentConfig[key] = requireHooksOptions[key](currentConfig[key], currentConfig);
                inProcessingFunction = false;
            });

            // wrap or define processCss function that collect generated css
            currentConfig.processCss = pushStylesCreator(currentConfig.processCss);

            require('css-modules-require-hook')(currentConfig);

            initialized = true;

            return options;
        },
        post() {
            // extract css only if is this option set
            if (thisPluginOptions && thisPluginOptions.extractCss) {
                // always rewrite file :-/
                extractCssFile(
                    process.cwd(),
                    cssMap,
                    thisPluginOptions.extractCss
                );
            }
        },
        visitor: {
            // import styles from './style.css';
            ImportDefaultSpecifier(path, { file }) {
                const { value } = path.parentPath.node.source;

                if (matchExtensions.test(value)) {
                    const requiringFile = file.opts.filename;
                    const tokens = requireCssFile(requiringFile, value);

                    path.parentPath.replaceWith(
                        t.variableDeclaration('var', [
                            t.variableDeclarator(
                                t.identifier(path.node.local.name),
                                buildClassNameToScopeNameMap(tokens)
                            )
                        ]),
                    );
                }
            },

            // const styles = require('./styles.css');
            CallExpression(path, { file }) {
                const { callee: { name: calleeName }, arguments: args } = path.node;

                if (calleeName !== 'require' || !args.length || !t.isStringLiteral(args[0])) {
                    return;
                }

                const [{ value: stylesheetPath }] = args;

                if (matchExtensions.test(stylesheetPath)) {
                    const requiringFile = file.opts.filename;
                    const tokens = requireCssFile(requiringFile, stylesheetPath);

                    // if parent expression is not a Program, replace expression with tokens
                    // Otherwise remove require from file, we just want to get generated css for our output
                    if (!t.isExpressionStatement(path.parent)) {
                        path.replaceWith(buildClassNameToScopeNameMap(tokens));
                    } else {
                        path.remove();
                    }
                }
            }
        }
    };

    return pluginApi;
}
<commit_msg>Renamed error param to prevent re-declaration<commit_after>import { resolve, dirname, isAbsolute } from 'path';

// options resolvers
import * as requireHooksOptions from './options_resolvers';

// utils.
import { extractCssFile } from './utils';

const defaultOptions = {
    generateScopedName: '[name]__[local]___[hash:base64:5]'
};

export default function transformCssModules({ types: t }) {
    function resolveModulePath(filename) {
        const dir = dirname(filename);
        if (isAbsolute(dir)) return dir;
        if (process.env.PWD) return resolve(process.env.PWD, dir);
        return resolve(dir);
    }

    /**
     *
     * @param {String} filepath     javascript file path
     * @param {String} cssFile      requireed css file path
     * @returns {Array} array of class names
     */
    function requireCssFile(filepath, cssFile) {
        let filePathOrModuleName = cssFile;

        // only resolve path to file when we have a file path
        if (!/^\w/i.test(filePathOrModuleName)) {
            const from = resolveModulePath(filepath);
            filePathOrModuleName = resolve(from, filePathOrModuleName);
        }

        // css-modules-require-hooks throws if file is ignored
        try {
            return require(filePathOrModuleName);
        } catch (e) {
            // As a last resort, require the cssFile itself. This enables loading of CSS files from external deps
            try {
                return require(cssFile);
            } catch (f) {
                return {}; // return empty object, this simulates result of ignored stylesheet file
            }
        }
    }

    // is css modules require hook initialized?
    let initialized = false;
    // are we requiring a module for preprocessCss, processCss, etc?
    // we don't want them to be transformed using this plugin
    // because it will cause circular dependency in babel-node and babel-register process
    let inProcessingFunction = false;

    let matchExtensions = /\.css$/i;

    function matcher(extensions = ['.css']) {
        const extensionsPattern = extensions.join('|').replace(/\./g, '\\\.');
        return new RegExp(`(${extensionsPattern})$`, 'i');
    }

    function buildClassNameToScopeNameMap(tokens) {
        /* eslint-disable new-cap */
        return t.ObjectExpression(
            Object.keys(tokens).map(token =>
                t.ObjectProperty(
                    t.StringLiteral(token),
                    t.StringLiteral(tokens[token])
                )
            )
        );
    }

    const cssMap = new Map();
    let thisPluginOptions = null;

    const pluginApi = {
        manipulateOptions(options) {
            if (initialized || inProcessingFunction) {
                return options;
            }

            // find options for this plugin
            // we have to use this hack because plugin.key does not have to be 'css-modules-transform'
            // so we will identify it by comparing manipulateOptions
            thisPluginOptions = options.plugins.filter(
              ([plugin]) => plugin.manipulateOptions === pluginApi.manipulateOptions
            )[0][1];

            const currentConfig = { ...defaultOptions, ...thisPluginOptions };
            // this is not a css-require-ook config
            delete currentConfig.extractCss;

            // match file extensions, speeds up transform by creating one
            // RegExp ahead of execution time
            matchExtensions = matcher(currentConfig.extensions);

            const pushStylesCreator = (toWrap) => (css, filepath) => {
                let processed;

                if (typeof toWrap === 'function') {
                    processed = toWrap(css, filepath);
                }

                if (typeof processed !== 'string') processed = css;

                // set css content only if is new
                if (!cssMap.has(filepath) || cssMap.get(filepath) !== processed) {
                    cssMap.set(filepath, processed);
                }

                return processed;
            };

            // resolve options
            Object.keys(requireHooksOptions).forEach(key => {
                // skip undefined options
                if (currentConfig[key] === undefined) {
                    return;
                }

                inProcessingFunction = true;
                currentConfig[key] = requireHooksOptions[key](currentConfig[key], currentConfig);
                inProcessingFunction = false;
            });

            // wrap or define processCss function that collect generated css
            currentConfig.processCss = pushStylesCreator(currentConfig.processCss);

            require('css-modules-require-hook')(currentConfig);

            initialized = true;

            return options;
        },
        post() {
            // extract css only if is this option set
            if (thisPluginOptions && thisPluginOptions.extractCss) {
                // always rewrite file :-/
                extractCssFile(
                    process.cwd(),
                    cssMap,
                    thisPluginOptions.extractCss
                );
            }
        },
        visitor: {
            // import styles from './style.css';
            ImportDefaultSpecifier(path, { file }) {
                const { value } = path.parentPath.node.source;

                if (matchExtensions.test(value)) {
                    const requiringFile = file.opts.filename;
                    const tokens = requireCssFile(requiringFile, value);

                    path.parentPath.replaceWith(
                        t.variableDeclaration('var', [
                            t.variableDeclarator(
                                t.identifier(path.node.local.name),
                                buildClassNameToScopeNameMap(tokens)
                            )
                        ]),
                    );
                }
            },

            // const styles = require('./styles.css');
            CallExpression(path, { file }) {
                const { callee: { name: calleeName }, arguments: args } = path.node;

                if (calleeName !== 'require' || !args.length || !t.isStringLiteral(args[0])) {
                    return;
                }

                const [{ value: stylesheetPath }] = args;

                if (matchExtensions.test(stylesheetPath)) {
                    const requiringFile = file.opts.filename;
                    const tokens = requireCssFile(requiringFile, stylesheetPath);

                    // if parent expression is not a Program, replace expression with tokens
                    // Otherwise remove require from file, we just want to get generated css for our output
                    if (!t.isExpressionStatement(path.parent)) {
                        path.replaceWith(buildClassNameToScopeNameMap(tokens));
                    } else {
                        path.remove();
                    }
                }
            }
        }
    };

    return pluginApi;
}
<|endoftext|>


<commit_before>/*
 * Module dependencies.
 */
var spawn = require('child_process').spawn;
var utils = require('./utils.js');
var report = require('./report.js');
var cinema4d = require('./cinema4d.js');

exports.report = report;
exports.app = cinema4d;

/**
 * This is the main render function.
 *
 * @param {Object} d
 * @public
 */
exports.render = function(d, callback) {
  /* Check if a filepath is set. if no filepath is set, we cannot render... */
  if (d.filepath === undefined) {
    utils.error('No CINEMA 4D file to render. Check the examples by running "c4d --help"');
  }
  /* Call the render... */
  else {
    execCinemaRender(d, function(c) {
      callback(c);
    });
  }
}

/**
 * This function execute the CINEMA 4D commandline interface with -render option.
 *
 * @param {Object} d
 * @private
 */
function execCinemaRender(d, callback) {
  /* Print the d object. used for development and debugging */
  //console.log(d);

  /* This is the cli options array we need to execute with the spawn function. */
  var tmpOptionsArray = checkOptions(d);
  /* Save the stdout, stderr data to variable. */
  var tmpStdoutData = [];
  var tmpStderrData = [];

  /* Execute the CINEMA 4D commandline interface. */
  var c4dRender = spawn(cinema4d.getPath(), tmpOptionsArray);
  c4dRender.stdout.on('data', function(data) {
    //console.log('VERSION: '+utils.getVersionFromStdout(data.toString()) );
    utils.log(d.silent, data.toString());
    tmpStdoutData.push(data.toString());
  });
  c4dRender.stderr.on('data', function(data) {
    utils.log(d.silent, 'Error: '+data.toString());
    tmpStderrData.push(data.toString());
  });
  c4dRender.on('close', function(code) {
    if (d.report) {
      var tmpData = {
        time: Date(),
        command_options: d,
        cinema4d_stdout: tmpStdoutData,
        cinema4d_stderr: tmpStderrData,
        code: code
      };
      report.write(d.report, tmpData, d.silent);
      callback(tmpData);
    };
    //utils.log(d.silent, 'Closed with code: '+code);
  });
}

/**
 * Check the Options comming from commander.js
 *
 * @param {Object} d
 * @return {Array}
 * @private
 */
function checkOptions(d) {
  var arr = [];

  arr.push(cinema4d.render.render.options[0]);
  arr.push(d.filepath);

  /* Check the different options... */
  if (d.frame !== undefined) {
    arr.push.apply(arr, cinema4d.optionFrame(d.frame));
  };
  if (d.oimage !== undefined) {
    arr.push.apply(arr, cinema4d.optionImage(d.oimage));
  };
  if (d.omultipass !== undefined) {
    arr.push.apply(arr, cinema4d.optionMultipass(d.omultipass));
  };
  if (d.oformat !== undefined) {
    arr.push.apply(arr, cinema4d.optionFormat(d.oformat));
  };
  if (d.oresolution !== undefined) {
    arr.push.apply(arr, cinema4d.optionResolution(d.oresolution));
  };
  if (d.threads !== undefined) {
    arr.push.apply(arr, cinema4d.optionThreads(d.threads));
  };
  if (d.gui === undefined) {
    arr.push(cinema4d.general.nogui.options[0]);
  };

  return arr;
}
<commit_msg>src/index.js initialize Cinema4D class<commit_after>/*
 * Module dependencies.
 */
var spawn = require('child_process').spawn;
var utils = require('./utils.js');
var report = require('./report.js');
var Cinema4d_Class = require('./cinema4d.js');

exports.report = report;
var cinema4d = new Cinema4d_Class.Cinema4D();
exports.app = cinema4d;

/**
 * This is the main render function.
 *
 * @param {Object} d
 * @public
 */
exports.render = function(d, callback) {
  /* Check if a filepath is set. if no filepath is set, we cannot render... */
  if (d.filepath === undefined) {
    utils.error('No CINEMA 4D file to render. Check the examples by running "c4d --help"');
  }
  /* Call the render... */
  else {
    execCinemaRender(d, function(c) {
      callback(c);
    });
  }
}

/**
 * This function execute the CINEMA 4D commandline interface with -render option.
 *
 * @param {Object} d
 * @private
 */
function execCinemaRender(d, callback) {
  /* Print the d object. used for development and debugging */
  //console.log(d);

  /* This is the cli options array we need to execute with the spawn function. */
  var tmpOptionsArray = checkOptions(d);
  /* Save the stdout, stderr data to variable. */
  var tmpStdoutData = [];
  var tmpStderrData = [];

  /* Execute the CINEMA 4D commandline interface. */
  var c4dRender = spawn(cinema4d.getPath(), tmpOptionsArray);
  c4dRender.stdout.on('data', function(data) {
    //console.log('VERSION: '+utils.getVersionFromStdout(data.toString()) );
    utils.log(d.silent, data.toString());
    tmpStdoutData.push(data.toString());
  });
  c4dRender.stderr.on('data', function(data) {
    utils.log(d.silent, 'Error: '+data.toString());
    tmpStderrData.push(data.toString());
  });
  c4dRender.on('close', function(code) {
    if (d.report) {
      var tmpData = {
        time: Date(),
        command_options: d,
        cinema4d_stdout: tmpStdoutData,
        cinema4d_stderr: tmpStderrData,
        code: code
      };
      report.write(d.report, tmpData, d.silent);
      callback(tmpData);
    };
    //utils.log(d.silent, 'Closed with code: '+code);
  });
}

/**
 * Check the Options comming from commander.js
 *
 * @param {Object} d
 * @return {Array}
 * @private
 */
function checkOptions(d) {
  var arr = [];

  arr.push(cinema4d.render.render.options[0]);
  arr.push(d.filepath);

  /* Check the different options... */
  if (d.frame !== undefined) {
    arr.push.apply(arr, cinema4d.optionFrame(d.frame));
  };
  if (d.oimage !== undefined) {
    arr.push.apply(arr, cinema4d.optionImage(d.oimage));
  };
  if (d.omultipass !== undefined) {
    arr.push.apply(arr, cinema4d.optionMultipass(d.omultipass));
  };
  if (d.oformat !== undefined) {
    arr.push.apply(arr, cinema4d.optionFormat(d.oformat));
  };
  if (d.oresolution !== undefined) {
    arr.push.apply(arr, cinema4d.optionResolution(d.oresolution));
  };
  if (d.threads !== undefined) {
    arr.push.apply(arr, cinema4d.optionThreads(d.threads));
  };
  if (d.gui === undefined) {
    arr.push(cinema4d.general.nogui.options[0]);
  };

  return arr;
}
<|endoftext|>


<commit_before>// Components
import Drawer from './Drawer';

export {
  Drawer,
};
<commit_msg>Updated require paths<commit_after>// Components
import PermanentDrawer from './Drawer/PermanentDrawer';
import TemporaryDrawer from './Drawer/TemporaryDrawer';

export { PermanentDrawer, TemporaryDrawer };
<|endoftext|>


<commit_before>import fs from 'fs';
import path from 'path';
import Walker from 'node-source-walk';
import q from 'q';
import walkdir from 'walkdir';
import _ from 'lodash';
import minimatch from 'minimatch';
import defaultParser from './parsers/default';
import gruntLoadTaskDetector from './detectors/gruntLoadTaskCallExpression';
import importDetector from './detectors/importDeclaration';
import requireDetector from './detectors/requireCallExpression';

function safeDetect(detector, node) {
  try {
    return detector(node);
  } catch (e) {
    return [];
  }
}

function getDependencies(parsers, detectors, filename) {
  return new Promise((resolve, reject) => {
    const ext = path.extname(filename);
    const parser = parsers[ext];

    if (parser) {
      fs.readFile(filename, 'utf8', (error, content) => {
        if (error) {
          reject(error);
        }

        try {
          const ast = parser(content);
          resolve(ast);
        } catch (syntaxError) {
          reject(syntaxError);
        }
      });
    } else {
      resolve(); // extension not supported
    }
  }).then(ast => {
    if (!ast) {
      return []; // unsupported extension return no dependencies
    }

    const walker = new Walker();
    let dependencies = [];

    walker.walk(ast, node => {
      const results = detectors.map(detector => safeDetect(detector, node));
      dependencies = dependencies.concat(...results);
    });

    return dependencies;
  });
}

function checkDirectory(dir, ignoreDirs, deps, devDeps) {
  const deferred = q.defer();
  const directoryPromises = [];
  const finder = walkdir(dir, { 'no_recurse': true });

  finder.on('directory', subdir => {
    if (_.contains(ignoreDirs, path.basename(subdir)))  {
      return;
    }

    directoryPromises.push(checkDirectory(subdir, ignoreDirs, deps, devDeps));
  });

  finder.on('file', filename => {
    const parsers = {
      '.js': defaultParser,
    };

    const detectors = [
      importDetector,
      requireDetector,
      gruntLoadTaskDetector,
    ];

    const promise = getDependencies(parsers, detectors, filename)
      .then(dependencies =>
        dependencies.map(dependency =>
          dependency.replace ? dependency.replace(/\/.*$/, '') : dependency))
      .then(used => ({
        dependencies: _.difference(deps, used),
        devDependencies: _.difference(devDeps, used),
      }), error => ({
        dependencies: deps,
        devDependencies: devDeps,
        invalidFiles: {
          [filename]: error,
        },
      }));

    directoryPromises.push(promise);
  });

  finder.on('end', () => {
    const value = Promise.all(directoryPromises).then(results =>
      results.reduce((obj, current) => ({
        dependencies: _.intersection(obj.dependencies, current.dependencies),
        devDependencies: _.intersection(obj.devDependencies, current.devDependencies),
        invalidFiles: _.merge(obj.invalidFiles, current.invalidFiles, {}),
        invalidDirs: _.merge(obj.invalidDirs, current.invalidDirs, {}),
      }), {
        dependencies: deps,
        devDependencies: devDeps,
        invalidFiles: {},
        invalidDirs: {},
      }));

    deferred.resolve(value);
  });

  finder.on('error', (dirPath, error) => {
    directoryPromises.push(Promise.resolve({
      dependencies: deps,
      devDependencies: devDeps,
      invalidDirs: {
        [dirPath]: error,
      },
    }));
  });

  return deferred.promise;
}

function isIgnored(ignoreMatches, dependency) {
  return _.any(ignoreMatches, match => {
    return minimatch(dependency, match);
  });
}

function hasBin(rootDir, dependency) {
  try {
    const depPkg = require(path.join(rootDir, 'node_modules', dependency, 'package.json'));
    return _.has(depPkg, 'bin');
  } catch (e) {
    return false;
  }
}

function filterDependencies(rootDir, ignoreMatches, dependencies) {
  return _(dependencies)
    .keys()
    .reject(dependency => hasBin(rootDir, dependency))
    .reject(dependency => isIgnored(ignoreMatches, dependency))
    .valueOf();
}

function depCheck(rootDir, options, cb) {
  const pkg = options.package || require(path.join(rootDir, 'package.json'));
  const deps = filterDependencies(rootDir, options.ignoreMatches, pkg.dependencies);
  const devDeps = filterDependencies(rootDir, options.ignoreMatches, options.withoutDev ? [] : pkg.devDependencies);

  const ignoreDirs =
    _([
      '.git',
      '.svn',
      '.hg',
      '.idea',
      'node_modules',
      'bower_components',
    ])
    .concat(options.ignoreDirs)
    .flatten()
    .unique()
    .valueOf();

  return checkDirectory(rootDir, ignoreDirs, deps, devDeps)
    .then(cb)
    .done();
}

module.exports = depCheck;
<commit_msg>Leverage ES6 promise and remove q.<commit_after>import fs from 'fs';
import path from 'path';
import Walker from 'node-source-walk';
import walkdir from 'walkdir';
import _ from 'lodash';
import minimatch from 'minimatch';
import defaultParser from './parsers/default';
import gruntLoadTaskDetector from './detectors/gruntLoadTaskCallExpression';
import importDetector from './detectors/importDeclaration';
import requireDetector from './detectors/requireCallExpression';

function safeDetect(detector, node) {
  try {
    return detector(node);
  } catch (e) {
    return [];
  }
}

function getDependencies(parsers, detectors, filename) {
  return new Promise((resolve, reject) => {
    const ext = path.extname(filename);
    const parser = parsers[ext];

    if (parser) {
      fs.readFile(filename, 'utf8', (error, content) => {
        if (error) {
          reject(error);
        }

        try {
          const ast = parser(content);
          resolve(ast);
        } catch (syntaxError) {
          reject(syntaxError);
        }
      });
    } else {
      resolve(); // extension not supported
    }
  }).then(ast => {
    if (!ast) {
      return []; // unsupported extension return no dependencies
    }

    const walker = new Walker();
    let dependencies = [];

    walker.walk(ast, node => {
      const results = detectors.map(detector => safeDetect(detector, node));
      dependencies = dependencies.concat(...results);
    });

    return dependencies;
  });
}

function checkDirectory(dir, ignoreDirs, deps, devDeps) {
  return new Promise(resolve => {
    const promises = [];
    const finder = walkdir(dir, { 'no_recurse': true });

    finder.on('directory', subdir => {
      if (_.contains(ignoreDirs, path.basename(subdir)))  {
        return;
      }

      promises.push(checkDirectory(subdir, ignoreDirs, deps, devDeps));
    });

    finder.on('file', filename => {
      const parsers = {
        '.js': defaultParser,
      };

      const detectors = [
        importDetector,
        requireDetector,
        gruntLoadTaskDetector,
      ];

      const promise = getDependencies(parsers, detectors, filename)
        .then(dependencies =>
          dependencies.map(dependency =>
            dependency.replace ? dependency.replace(/\/.*$/, '') : dependency))
        .then(used => ({
          dependencies: _.difference(deps, used),
          devDependencies: _.difference(devDeps, used),
        }), error => ({
          dependencies: deps,
          devDependencies: devDeps,
          invalidFiles: {
            [filename]: error,
          },
        }));

      promises.push(promise);
    });

    finder.on('end', () => {
      const value = Promise.all(promises).then(results =>
        results.reduce((obj, current) => ({
          dependencies: _.intersection(obj.dependencies, current.dependencies),
          devDependencies: _.intersection(obj.devDependencies, current.devDependencies),
          invalidFiles: _.merge(obj.invalidFiles, current.invalidFiles, {}),
          invalidDirs: _.merge(obj.invalidDirs, current.invalidDirs, {}),
        }), {
          dependencies: deps,
          devDependencies: devDeps,
          invalidFiles: {},
          invalidDirs: {},
        }));

      resolve(value);
    });

    finder.on('error', (dirPath, error) => {
      promises.push(Promise.resolve({
        dependencies: deps,
        devDependencies: devDeps,
        invalidDirs: {
          [dirPath]: error,
        },
      }));
    });
  });
}

function isIgnored(ignoreMatches, dependency) {
  return _.any(ignoreMatches, match => {
    return minimatch(dependency, match);
  });
}

function hasBin(rootDir, dependency) {
  try {
    const depPkg = require(path.join(rootDir, 'node_modules', dependency, 'package.json'));
    return _.has(depPkg, 'bin');
  } catch (e) {
    return false;
  }
}

function filterDependencies(rootDir, ignoreMatches, dependencies) {
  return _(dependencies)
    .keys()
    .reject(dependency => hasBin(rootDir, dependency))
    .reject(dependency => isIgnored(ignoreMatches, dependency))
    .valueOf();
}

function depCheck(rootDir, options, cb) {
  const pkg = options.package || require(path.join(rootDir, 'package.json'));
  const deps = filterDependencies(rootDir, options.ignoreMatches, pkg.dependencies);
  const devDeps = filterDependencies(rootDir, options.ignoreMatches, options.withoutDev ? [] : pkg.devDependencies);

  const ignoreDirs =
    _([
      '.git',
      '.svn',
      '.hg',
      '.idea',
      'node_modules',
      'bower_components',
    ])
    .concat(options.ignoreDirs)
    .flatten()
    .unique()
    .valueOf();

  return checkDirectory(rootDir, ignoreDirs, deps, devDeps).then(cb);
}

module.exports = depCheck;
<|endoftext|>


<commit_before>class Config {
  constructor() {
    this.separator = {
      element: '__',
      modifier: '--'
    };
  }

  setSeparator(element, modifier = '--') {
    this.separator = {element, modifier};
  }
}

export const config = new Config();

export default function nbem() {
  const clses = [];

  function _nbem(rawCls) {
    const nests = rawCls.split('&');
    const length = nests.length - 1;
    clses[length] = nests[length];
    const cls = clses.map((c, key) => {
      if (key <= length) {
        return c.split(':').join(config.separator.modifier);
      }
    }).filter(c => c).join(config.separator.element);
    return cls;
  }

  return _nbem;
}
<commit_msg>feat(nbem): config add init method<commit_after>class Config {
  constructor() {
    this.init();
  }

  init() {
    this.separator = {
      element: '__',
      modifier: '--'
    };
  }

  setSeparator(element, modifier = '--') {
    this.separator = {element, modifier};
  }
}

export const config = new Config();

export default function nbem() {
  const clses = [];

  function _nbem(rawCls) {
    const nests = rawCls.split('&');
    const length = nests.length - 1;
    clses[length] = nests[length];
    const cls = clses.map((c, key) => {
      if (key <= length) {
        return c.split(':').join(config.separator.modifier);
      }
    }).filter(c => c).join(config.separator.element);
    return cls;
  }

  return _nbem;
}
<|endoftext|>


<commit_before>import * as jmp from 'jmp';
import * as uuid from 'uuid';

import { Observer, Observable, Subject } from 'rx';

function formConnectionString(config, channel) {
  const portDelimiter = config.transport === 'tcp' ? ':' : '-';
  const port = config[channel + '_port'];
  if (! port) {
    throw new Error(`Port not found for channel "${channel}"`);
  }
  return `${config.transport}://${config.ip}${portDelimiter}${port}`;
}

function sendMessage(socket, messageObject) {
  const message = new jmp.Message(messageObject);
  socket.send(message);
}

function createObserver(jmpSocket) {
  return Observer.create(messageObject => {
    sendMessage(jmpSocket, messageObject);
  }, err => {
    // We don't expect to send errors to the kernel
    console.error(err);
  }, () => {
    // tear it down, tear it *all* down
    jmpSocket.removeAllListeners();
    jmpSocket.close();
  });
}

function createObservable(jmpSocket) {
  return Observable.fromEvent(jmpSocket, 'message')
                   .map(msg => {
                     // Conform to same message format as notebook websockets
                     // See https://github.com/n-riesco/jmp/issues/10
                     delete msg.idents;
                     delete msg.signatureOK;
                     delete msg.blobs;
                     return msg;
                   })
                   .publish()
                   .refCount();
}

function createSubject(jmpSocket) {
  const subj = Subject.create(createObserver(jmpSocket),
                              createObservable(jmpSocket));
  subj.send = subj.onNext; // Adapt naming to fit our parlance
  subj.close = subj.onCompleted;
  return subj;
}

function createSocket(type, channel, config) {
  const scheme = config.signature_scheme.slice('hmac-'.length);
  const socket = new jmp.Socket(type, scheme, config.key);
  socket.identity = channel + uuid.v4();
  socket.connect(formConnectionString(config, channel));
  return socket;
}

function enchannelZMQ(config) {
  const shellSocket = createSocket('dealer', 'shell', config);
  const controlSocket = createSocket('dealer', 'control', config);
  const stdinSocket = createSocket('dealer', 'stdin', config);
  const iopubSocket = createSocket('sub', 'iopub', config);

  iopubSocket.subscribe('');

  return {
    shell: createSubject(shellSocket),
    control: createSubject(controlSocket),
    iopub: createSubject(iopubSocket),
    stdin: createSubject(stdinSocket),
  };
}

module.exports = enchannelZMQ;
<commit_msg>Deep freeze messages before publishing stream<commit_after>import * as jmp from 'jmp';
import * as uuid from 'uuid';

import { Observer, Observable, Subject } from 'rx';

function formConnectionString(config, channel) {
  const portDelimiter = config.transport === 'tcp' ? ':' : '-';
  const port = config[channel + '_port'];
  if (! port) {
    throw new Error(`Port not found for channel "${channel}"`);
  }
  return `${config.transport}://${config.ip}${portDelimiter}${port}`;
}

function sendMessage(socket, messageObject) {
  const message = new jmp.Message(messageObject);
  socket.send(message);
}

function createObserver(jmpSocket) {
  return Observer.create(messageObject => {
    sendMessage(jmpSocket, messageObject);
  }, err => {
    // We don't expect to send errors to the kernel
    console.error(err);
  }, () => {
    // tear it down, tear it *all* down
    jmpSocket.removeAllListeners();
    jmpSocket.close();
  });
}

// To make obj fully immutable, freeze each object in obj.
// To do so, we use this function.
function deepFreeze(obj) {
  // Freeze properties before freezing self
  Object.getOwnPropertyNames(obj).forEach(name => {
    const prop = obj[name];
    if(typeof prop === 'object' && prop !== null && !Object.isFrozen(prop)) {
      deepFreeze(prop);
    }
  });
  // Freeze self
  return Object.freeze(obj);
}

function createObservable(jmpSocket) {
  return Observable.fromEvent(jmpSocket, 'message')
                   .map(msg => {
                     // Conform to same message format as notebook websockets
                     // See https://github.com/n-riesco/jmp/issues/10
                     delete msg.idents;
                     delete msg.signatureOK;
                     delete msg.blobs;
                     // Deep freeze the message
                     deepFreeze(msg);
                     return msg;
                   })
                   .publish()
                   .refCount();
}

function createSubject(jmpSocket) {
  const subj = Subject.create(createObserver(jmpSocket),
                              createObservable(jmpSocket));
  subj.send = subj.onNext; // Adapt naming to fit our parlance
  subj.close = subj.onCompleted;
  return subj;
}

function createSocket(type, channel, config) {
  const scheme = config.signature_scheme.slice('hmac-'.length);
  const socket = new jmp.Socket(type, scheme, config.key);
  socket.identity = channel + uuid.v4();
  socket.connect(formConnectionString(config, channel));
  return socket;
}

function enchannelZMQ(config) {
  const shellSocket = createSocket('dealer', 'shell', config);
  const controlSocket = createSocket('dealer', 'control', config);
  const stdinSocket = createSocket('dealer', 'stdin', config);
  const iopubSocket = createSocket('sub', 'iopub', config);

  iopubSocket.subscribe('');

  return {
    shell: createSubject(shellSocket),
    control: createSubject(controlSocket),
    iopub: createSubject(iopubSocket),
    stdin: createSubject(stdinSocket),
  };
}

module.exports = enchannelZMQ;
<|endoftext|>


<commit_before>import H1 from './Components/H1';
import H2 from './Components/H2';
import BusyModal from './Components/BusyModal';
import TextInput from './Components/TextInput';
import ErrorAlert from './Components/ErrorAlert';
import Container from './Components/Container';
import Card from './Components/Card';
import Spinner from './Components/Spinner';
import Platform from './Components/Platform';
import Header from './Components/Header';
import SpinnerCard from './Components/SpinnerCard';
import SimpleTextCard from './Components/SimpleTextCard';

export {
  H1,
  H2,
  BusyModal,
  TextInput,
  ErrorAlert,
  Container,
  Card,
  Spinner,
  Platform,
  Header,
  SpinnerCard,
  SimpleTextCard,
};
<commit_msg>Fixed issue with CenterView not being included<commit_after>import H1 from './Components/H1';
import H2 from './Components/H2';
import BusyModal from './Components/BusyModal';
import TextInput from './Components/TextInput';
import ErrorAlert from './Components/ErrorAlert';
import Container from './Components/Container';
import Card from './Components/Card';
import Spinner from './Components/Spinner';
import Platform from './Components/Platform';
import Header from './Components/Header';
import SpinnerCard from './Components/SpinnerCard';
import SimpleTextCard from './Components/SimpleTextCard';
import CenterView from './Components/CenterView';

export {
  H1,
  H2,
  BusyModal,
  TextInput,
  ErrorAlert,
  Container,
  Card,
  Spinner,
  Platform,
  Header,
  SpinnerCard,
  SimpleTextCard,
  CenterView,
};
<|endoftext|>


<commit_before>const express = require('express');
const bodyParser = require('body-parser');
const createClient = require('@rabblerouser/stream-client');

const config = require('./config');
const sendRegistrationEmail = require('./sendRegistrationEmail')

const app = express();
app.use(bodyParser.json());

const streamClientSettings = {
  listenWithAuthToken: config.listenerAuthToken,
};
const streamClient = createClient(streamClientSettings);

streamClient.on('member-registered', member => sendRegistrationEmail(member.email));
app.post('/mail', streamClient.listen());

app.listen(3001, () => {
  console.log('Listening for events');
});
<commit_msg>Change endpoint to /events for consistency<commit_after>const express = require('express');
const bodyParser = require('body-parser');
const createClient = require('@rabblerouser/stream-client');

const config = require('./config');
const sendRegistrationEmail = require('./sendRegistrationEmail')

const app = express();
app.use(bodyParser.json());

const streamClientSettings = {
  listenWithAuthToken: config.listenerAuthToken,
};
const streamClient = createClient(streamClientSettings);

streamClient.on('member-registered', member => sendRegistrationEmail(member.email));
app.post('/events', streamClient.listen());

app.listen(3001, () => {
  console.log('Listening for events');
});
<|endoftext|>


<commit_before>import { Map } from 'extendable-immutable'

/**
 * A library for creating affine transform matrix (3x3) that are Immutable.
 * These matrices can be used for matrix calcuations on SVG CTMs (current transform matrix).
 *
 * @module immutable-transform-matrix
 * @example
 * import { Matrix } from 'immutable-transform-matrix'
 * import { isImmutable } from 'immutable'
 * const m1 = new Matrix()
 * isImmutable(m1) // true
 * const m2 = m1.translate(10, 20)
 */

/**
 * @class Matrix
 * @extends Immutable.Map
 */
class Matrix extends Map {
  /**
   * Construct a Matrix. Creates an Identiy matrix if no params are supplied.
   * @param {number} a
   * @param {number} b
   * @param {number} c
   * @param {number} d
   * @param {number} e
   * @param {number} f
   */
  constructor (...args) {
    if (args.length > 0) {
      super({
        a: args[0],
        b: args[1],
        c: args[2],
        d: args[3],
        e: args[4],
        f: args[5]
      })
    } else {
      super({
        a: 1,
        b: 0,
        c: 0,
        d: 1,
        e: 0,
        f: 0
      })
    }
  }

  /**
   * Multiplies current matrix with new matrix values.
   * @param {number} a2 - scale x
   * @param {number} b2 - shear y
   * @param {number} c2 - shear x
   * @param {number} d2 - scale y
   * @param {number} e2 - translate x
   * @param {number} f2 - translate y
   * @return {Matrix}
   */
  transform (a2, b2, c2, d2, e2, f2) {
    const a1 = this.get('a')
    const b1 = this.get('b')
    const c1 = this.get('c')
    const d1 = this.get('d')
    const e1 = this.get('e')
    const f1 = this.get('f')

    return this.withMutations(matrix => matrix
      .set('a', (a1 * a2) + (c1 * b2))
      .set('b', (b1 * a2) + (d1 * b2))
      .set('c', a1 * c2 + c1 * d2)
      .set('d', b1 * c2 + d1 * d2)
      .set('e', a1 * e2 + c1 * f2 + e1)
      .set('f', b1 * e2 + d1 * f2 + f1)
    )
  }

  /**
   * Scales current matrix accumulative.
   * If the second param is ommitted it scale uniformly.
   * @param {number} sx - scale factor x (1 does nothing)
   * @param {number} [sy] - scale factor y (1 does nothing)
   * @return {Matrix}
   */
  scale (...args) {
    const sx = args[0]
    let sy = sx
    if (args.length > 1) {
      sy = args[1]
    }
    return this.transform(sx, 0, 0, sy, 0, 0)
  }

  /**
   * Translate current matrix accumulative.
   * @param {number} tx - translation for x
   * @param {number} ty - translation for y
   * @return {Matrix}
   */
  translate (tx, ty) {
    return this.transform(1, 0, 0, 1, tx, ty)
  }

  /**
   * Rotates current matrix accumulative by angle.
   * @param {number} angle - angle in radians
   */
  rotate (angle) {
    var cos = Math.cos(angle)
    var sin = Math.sin(angle)
    return this.transform(cos, sin, -sin, cos, 0, 0)
  }

  /**
   * Helper method to make a rotation based on an angle in degrees.
   * @param {number} angle - angle in degrees
   */
  rotateDeg (angle) {
    return this.rotate(angle * Math.PI / 180)
  }
}

export default Matrix
<commit_msg>feat: multiply<commit_after>import { Map } from 'extendable-immutable'

/**
 * A library for creating affine transform matrix (3x3) that are Immutable.
 * These matrices can be used for matrix calcuations on SVG CTMs (current transform matrix).
 *
 * @module immutable-transform-matrix
 * @example
 * import { Matrix } from 'immutable-transform-matrix'
 * import { isImmutable } from 'immutable'
 * const m1 = new Matrix()
 * isImmutable(m1) // true
 * const m2 = m1.translate(10, 20)
 */

/**
 * @class Matrix
 * @extends Immutable.Map
 */
class Matrix extends Map {
  /**
   * Construct a Matrix. Creates an Identiy matrix if no params are supplied.
   * @param {number} a
   * @param {number} b
   * @param {number} c
   * @param {number} d
   * @param {number} e
   * @param {number} f
   */
  constructor (...args) {
    if (args.length > 0) {
      super({
        a: args[0],
        b: args[1],
        c: args[2],
        d: args[3],
        e: args[4],
        f: args[5]
      })
    } else {
      super({
        a: 1,
        b: 0,
        c: 0,
        d: 1,
        e: 0,
        f: 0
      })
    }
  }

  /**
   * Multiplies current matrix with new matrix values.
   * @param {number} a2 - scale x
   * @param {number} b2 - shear y
   * @param {number} c2 - shear x
   * @param {number} d2 - scale y
   * @param {number} e2 - translate x
   * @param {number} f2 - translate y
   * @return {Matrix}
   */
  transform (a2, b2, c2, d2, e2, f2) {
    const a1 = this.get('a')
    const b1 = this.get('b')
    const c1 = this.get('c')
    const d1 = this.get('d')
    const e1 = this.get('e')
    const f1 = this.get('f')

    return this.withMutations(matrix => matrix
      .set('a', (a1 * a2) + (c1 * b2))
      .set('b', (b1 * a2) + (d1 * b2))
      .set('c', a1 * c2 + c1 * d2)
      .set('d', b1 * c2 + d1 * d2)
      .set('e', a1 * e2 + c1 * f2 + e1)
      .set('f', b1 * e2 + d1 * f2 + f1)
    )
  }

  /**
   * Scales current matrix accumulative.
   * If the second param is ommitted it scale uniformly.
   * @param {number} sx - scale factor x (1 does nothing)
   * @param {number} [sy] - scale factor y (1 does nothing)
   * @return {Matrix}
   */
  scale (...args) {
    const sx = args[0]
    let sy = sx
    if (args.length > 1) {
      sy = args[1]
    }
    return this.transform(sx, 0, 0, sy, 0, 0)
  }

  /**
   * Translate current matrix accumulative.
   * @param {number} tx - translation for x
   * @param {number} ty - translation for y
   * @return {Matrix}
   */
  translate (tx, ty) {
    return this.transform(1, 0, 0, 1, tx, ty)
  }

  /**
   * Rotates current matrix accumulative by angle.
   * @param {number} angle - angle in radians
   * @return {Matrix}
   */
  rotate (angle) {
    var cos = Math.cos(angle)
    var sin = Math.sin(angle)
    return this.transform(cos, sin, -sin, cos, 0, 0)
  }

  /**
   * Helper method to make a rotation based on an angle in degrees.
   * @param {number} angle - angle in degrees
   * @return {Matrix}
   */
  rotateDeg (angle) {
    return this.rotate(angle * Math.PI / 180)
  }

  /**
   * Multiplies current matrix with an other matrix.
   * @param {Matrix} m - the other matrix
   * @return {Matrix}
   */
  multiply (matrix) {
    return this.transform(
      matrix.get('a'),
      matrix.get('b'),
      matrix.get('c'),
      matrix.get('d'),
      matrix.get('e'),
      matrix.get('f')
    )
  }
}

export default Matrix
<|endoftext|>


<commit_before>/*jshint bitwise: false*/

(function (w) {
  'use strict';

  function getEndianness() {
    var a = new ArrayBuffer(4);
    var b = new Uint8Array(a);
    var c = new Uint32Array(a);
    b[0] = 0xa1;
    b[1] = 0xb2;
    b[2] = 0xc3;
    b[3] = 0xd4;
    if (c[0] === 0xd4c3b2a1) {
      return BlobReader.ENDIANNESS.LITTLE_ENDIAN;
    }
    if (c[0] === 0xa1b2c3d4) {
      return BlobReader.ENDIANNESS.BIG_ENDIAN;
    } else {
      throw new Error('Unrecognized endianness');
    }
  }
  /**
   * Constructor function for the blob reader.
   *
   * @public
   * @constructor
   * @param {Blob} blob The blob object, which should be read
   * @param {BlobReader.ENDIANNESS} dataEndianness Endianness of the
   *  expected data
   * @param {BlobReader.ENDIANNESS} endianness System endianness
   */
  function BlobReader(blob, dataEndianness, endianness) {
    if (!(this instanceof BlobReader)) {
      return new BlobReader(blob, dataEndianness, endianness);
    }
    this._blob = blob;
    this._position = 0;
    this._queue = [];
    this._currentEndianness = endianness || getEndianness();
    this._dataEndianness = dataEndianness || this._currentEndianness;
    this._pendingTask = false;
    this._currentResult = null;
  }

  BlobReader.ARRAY_BUFFER = 'ArrayBuffer';
  BlobReader.BINARY_STRING = 'BinaryString';
  BlobReader.TEXT = 'Text';
  BlobReader.DATA_URL = 'DataURL';
  BlobReader.BLOB = 'Blob';

  BlobReader.ENDIANNESS = {
    BIG_ENDIAN: 'BIG_ENDIAN',
    LITTLE_ENDIAN: 'LITTLE_ENDIAN'
  };

  BlobReader.prototype.setDataEndianness = function (endianness) {
    this._dataEndianness = endianness;
  };

  /* jshint validthis: true */
  function invokeNext() {

    function done(data) {
      current.cb(data);
      this._pendingTask = false;
      this._position += current.count;
      invokeNext.call(this);
    }

    var current = this._queue.shift();
    if (!current) {
      return;
    }
    if (this._position + current.count > this._blob.size) {
      throw new Error('Limit reached. Trying to read ' +
          (this._position + current.count) + ' bytes out of ' +
          this._blob.size + '.');
    }
    if (!current.type) {
      current.type = BlobReader.BINARY_STRING;
    }
    var slice = this._blob
      .slice(this._position, this._position + current.count);
    if (current.type === BlobReader.BLOB) {
      done.call(this, slice);
    } else {
      var reader = new FileReader();
      this._pendingTask = true;
      reader.onload = function (e) {
        done.call(this, e.target.result);
      }.bind(this);
      reader.onerror = function () {
        throw new Error('Error while reading the blob');
      };
      reader['readAs' + current.type](slice);
    }
  }

  /**
   * Read definite amount of bytes by the blob
   *
   * @public
   * @param {Number} count The count of bytes, which should be read
   * @param {Function} cb The callback, which should be
   *  invoked once the bytes are read
   * @return {BlobReader} Returns `this`
   */
  BlobReader.prototype.read = function (count, type, cb) {
    if (typeof count === 'string') {
      cb = type;
      count = undefined;
      type = count;
    }
    if (count === undefined) {
      count = this._blob.size - this._position;
    }
    if (typeof count === 'function') {
      cb = count;
      type = undefined;
      count = this._blob.size - this._position;
    }
    if (typeof type === 'function') {
      cb = type;
      type = undefined;
    }
    this._queue.push({
      count: count,
      cb: cb,
      type: type
    });
    if (!this._pendingTask) {
      invokeNext.call(this);
    }
    return this;
  };

  /**
   * Read defined amount of bytes as text
   *
   * @public
   * @param {Number} count Number of bytes to be read
   * @param {Function} cb Calback to be invoked
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readText = function (count, cb) {
    return this.read(count, BlobReader.TEXT, cb);
  };

  /**
   * Read defined amount of bytes as array buffer
   *
   * @public
   * @param {Number} count Number of bytes to be read
   * @param {Function} cb Calback to be invoked
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readArrayBuffer = function (count, cb) {
    return this.read(count, BlobReader.ARRAY_BUFFER, cb);
  };

  /**
   * Read defined amount of bytes as binary string
   *
   * @public
   * @param {Number} count Number of bytes to be read
   * @param {Function} cb Calback to be invoked
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readBinaryString = function (count, cb) {
    return this.read(count, BlobReader.BINARY_STRING, cb);
  };

  /**
   * Read defined amount of bytes as data url
   *
   * @public
   * @param {Number} count Number of bytes to be read
   * @param {Function} cb Calback to be invoked
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readDataURL = function (count, cb) {
    return this.read(count, BlobReader.DATA_URL, cb);
  };

  function swap(arr, cb) {
    for (var i = 0; i < arr.length; i += 1) {
      arr[i] = cb(arr[i]);
    }
    return arr;
  }

  var byteFormatter = {
    swap8: function (arr) {
      return swap(arr, function (val) {
        return val;
      });
    },
    swap16: function (arr) {
      return swap(arr, function (val) {
        return ((val & 0xFF) << 8) |
               ((val >> 8) & 0xFF);
      });
    },
    swap32: function (arr) {
      return swap(arr, function (val) {
        return ((val & 0xFF) << 24) |
               ((val & 0xFF00) << 8) |
               ((val >> 8) & 0xFF00) |
               ((val >> 24) & 0xFF);
      });
    }
  };

  /* jshint validthis: true */
  function uintReader(name, count, octets, endianness) {
    if (!this._currentResult) {
      this._currentResult = {};
    }
    count = (count || 1) * octets;
    var callback = function (data) {
      var bitsNum = 8 * octets;
      var type = window['Uint' + bitsNum + 'Array'];
      data = new type(data);
      if (this._currentEndianness !== endianness) {
        data = byteFormatter['swap' + bitsNum](data);
      }
      if (count === octets) {
        data = data[0];
      }
      this._currentResult[name] = data;
    }.bind(this);
    return this.readArrayBuffer(count, callback);
  }

  /**
   * Read defined amount of bytes as uint8 array
   *
   * @public
   * @param {String} name Property name
   * @param {Number} count Number of 8 bit numbers to be read
   * @param {BlobReader.ENDIANNESS} endianness Endianness of the
   *  bytes which should be read. If differ from the system's endianness
   *  the values will be converted
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readUint8 = function (name, count, endianness) {
    return uintReader.call(this, name, count, 1,
           endianness || this._dataEndianness);
  };

  /**
   * Read defined amount of bytes as uint16 array
   *
   * @public
   * @param {String} name Property name
   * @param {Number} count Number of 16 bit numbers to be read
   * @param {BlobReader.ENDIANNESS} endianness Endianness of the
   *  bytes which should be read. If differ from the system's endianness
   *  the values will be converted
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readUint16 = function (name, count, endianness) {
    return uintReader.call(this, name, count, 2,
           endianness || this._dataEndianness);
  };

  /**
   * Read defined amount of bytes as uint32 array
   *
   * @public
   * @param {String} name Property name
   * @param {Number} count Number of 32 bit numbers to be read
   * @param {BlobReader.ENDIANNESS} endianness Endianness of the
   *  bytes which should be read. If differ from the system's endianness
   *  the values will be converted
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readUint32 = function (name, count, endianness) {
    return uintReader.call(this, name, count, 4,
           endianness || this._dataEndianness);
  };

  /**
   * Read a blob and push it to the result object
   *
   * @public
   * @param {String} name Property name
   * @param {Number} count Number of bytes to be sliced from the Blob
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readBlob = function (name, count) {
    this._queue.push({
      count: count,
      type: BlobReader.BLOB,
      cb: function (result) {
        this._currentResult[name] = result;
      }.bind(this)
    });
    return this;
  };

  /**
   * Gets the result object
   *
   * @public
   * @return {Object} The object resulted from the calls of readUint
   */
  BlobReader.prototype.commit = function (cb) {
    if (!this._currentResult) {
      throw new Error('Cannot commit without any reads');
    }
    var res = this._currentResult;
    var task = {
      count: 0,
      type: BlobReader.BLOB,
      cb: function () {
        cb(res);
        this._currentResult = null;
      }.bind(this)
    };
    this._queue.push(task);
    return this;
  };

  w.BlobReader = BlobReader;

}(window));
<commit_msg>Add skip method<commit_after>/*jshint bitwise: false*/

(function (w) {
  'use strict';

  function getEndianness() {
    var a = new ArrayBuffer(4);
    var b = new Uint8Array(a);
    var c = new Uint32Array(a);
    b[0] = 0xa1;
    b[1] = 0xb2;
    b[2] = 0xc3;
    b[3] = 0xd4;
    if (c[0] === 0xd4c3b2a1) {
      return BlobReader.ENDIANNESS.LITTLE_ENDIAN;
    }
    if (c[0] === 0xa1b2c3d4) {
      return BlobReader.ENDIANNESS.BIG_ENDIAN;
    } else {
      throw new Error('Unrecognized endianness');
    }
  }
  /**
   * Constructor function for the blob reader.
   *
   * @public
   * @constructor
   * @param {Blob} blob The blob object, which should be read
   * @param {BlobReader.ENDIANNESS} dataEndianness Endianness of the
   *  expected data
   * @param {BlobReader.ENDIANNESS} endianness System endianness
   */
  function BlobReader(blob, dataEndianness, endianness) {
    if (!(this instanceof BlobReader)) {
      return new BlobReader(blob, dataEndianness, endianness);
    }
    this._blob = blob;
    this._position = 0;
    this._queue = [];
    this._currentEndianness = endianness || getEndianness();
    this._dataEndianness = dataEndianness || this._currentEndianness;
    this._pendingTask = false;
    this._currentResult = null;
  }

  BlobReader.ARRAY_BUFFER = 'ArrayBuffer';
  BlobReader.BINARY_STRING = 'BinaryString';
  BlobReader.TEXT = 'Text';
  BlobReader.DATA_URL = 'DataURL';
  BlobReader.BLOB = 'Blob';

  BlobReader.ENDIANNESS = {
    BIG_ENDIAN: 'BIG_ENDIAN',
    LITTLE_ENDIAN: 'LITTLE_ENDIAN'
  };

  BlobReader.prototype.setDataEndianness = function (endianness) {
    this._dataEndianness = endianness;
  };

  /* jshint validthis: true */
  function invokeNext() {

    function done(data) {
      current.cb(data);
      this._pendingTask = false;
      this._position += current.count;
      invokeNext.call(this);
    }

    var current = this._queue.shift();
    if (!current) {
      return;
    }
    if (this._position + current.count > this._blob.size) {
      throw new Error('Limit reached. Trying to read ' +
          (this._position + current.count) + ' bytes out of ' +
          this._blob.size + '.');
    }
    if (!current.type) {
      current.type = BlobReader.BINARY_STRING;
    }
    var slice = this._blob
      .slice(this._position, this._position + current.count);
    if (current.type === BlobReader.BLOB) {
      done.call(this, slice);
    } else {
      var reader = new FileReader();
      this._pendingTask = true;
      reader.onload = function (e) {
        done.call(this, e.target.result);
      }.bind(this);
      reader.onerror = function () {
        throw new Error('Error while reading the blob');
      };
      reader['readAs' + current.type](slice);
    }
  }

  /**
   * Read definite amount of bytes by the blob
   *
   * @public
   * @param {Number} count The count of bytes, which should be read
   * @param {Function} cb The callback, which should be
   *  invoked once the bytes are read
   * @return {BlobReader} Returns `this`
   */
  BlobReader.prototype.read = function (count, type, cb) {
    if (typeof count === 'string') {
      cb = type;
      count = undefined;
      type = count;
    }
    if (count === undefined) {
      count = this._blob.size - this._position;
    }
    if (typeof count === 'function') {
      cb = count;
      type = undefined;
      count = this._blob.size - this._position;
    }
    if (typeof type === 'function') {
      cb = type;
      type = undefined;
    }
    this._queue.push({
      count: count,
      cb: cb,
      type: type
    });
    if (!this._pendingTask) {
      invokeNext.call(this);
    }
    return this;
  };

  /**
   * Read defined amount of bytes as text
   *
   * @public
   * @param {Number} count Number of bytes to be read
   * @param {Function} cb Calback to be invoked
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readText = function (count, cb) {
    return this.read(count, BlobReader.TEXT, cb);
  };

  /**
   * Read defined amount of bytes as array buffer
   *
   * @public
   * @param {Number} count Number of bytes to be read
   * @param {Function} cb Calback to be invoked
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readArrayBuffer = function (count, cb) {
    return this.read(count, BlobReader.ARRAY_BUFFER, cb);
  };

  /**
   * Read defined amount of bytes as binary string
   *
   * @public
   * @param {Number} count Number of bytes to be read
   * @param {Function} cb Calback to be invoked
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readBinaryString = function (count, cb) {
    return this.read(count, BlobReader.BINARY_STRING, cb);
  };

  /**
   * Read defined amount of bytes as data url
   *
   * @public
   * @param {Number} count Number of bytes to be read
   * @param {Function} cb Calback to be invoked
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readDataURL = function (count, cb) {
    return this.read(count, BlobReader.DATA_URL, cb);
  };

  function swap(arr, cb) {
    for (var i = 0; i < arr.length; i += 1) {
      arr[i] = cb(arr[i]);
    }
    return arr;
  }

  var byteFormatter = {
    swap8: function (arr) {
      return swap(arr, function (val) {
        return val;
      });
    },
    swap16: function (arr) {
      return swap(arr, function (val) {
        return ((val & 0xFF) << 8) |
               ((val >> 8) & 0xFF);
      });
    },
    swap32: function (arr) {
      return swap(arr, function (val) {
        return ((val & 0xFF) << 24) |
               ((val & 0xFF00) << 8) |
               ((val >> 8) & 0xFF00) |
               ((val >> 24) & 0xFF);
      });
    }
  };

  /* jshint validthis: true */
  function uintReader(name, count, octets, endianness) {
    if (!this._currentResult) {
      this._currentResult = {};
    }
    count = (count || 1) * octets;
    var callback = function (data) {
      var bitsNum = 8 * octets;
      var type = window['Uint' + bitsNum + 'Array'];
      data = new type(data);
      if (this._currentEndianness !== endianness) {
        data = byteFormatter['swap' + bitsNum](data);
      }
      if (count === octets) {
        data = data[0];
      }
      this._currentResult[name] = data;
    }.bind(this);
    return this.readArrayBuffer(count, callback);
  }

  /**
   * Read defined amount of bytes as uint8 array
   *
   * @public
   * @param {String} name Property name
   * @param {Number} count Number of 8 bit numbers to be read
   * @param {BlobReader.ENDIANNESS} endianness Endianness of the
   *  bytes which should be read. If differ from the system's endianness
   *  the values will be converted
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readUint8 = function (name, count, endianness) {
    return uintReader.call(this, name, count, 1,
           endianness || this._dataEndianness);
  };

  /**
   * Read defined amount of bytes as uint16 array
   *
   * @public
   * @param {String} name Property name
   * @param {Number} count Number of 16 bit numbers to be read
   * @param {BlobReader.ENDIANNESS} endianness Endianness of the
   *  bytes which should be read. If differ from the system's endianness
   *  the values will be converted
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readUint16 = function (name, count, endianness) {
    return uintReader.call(this, name, count, 2,
           endianness || this._dataEndianness);
  };

  /**
   * Read defined amount of bytes as uint32 array
   *
   * @public
   * @param {String} name Property name
   * @param {Number} count Number of 32 bit numbers to be read
   * @param {BlobReader.ENDIANNESS} endianness Endianness of the
   *  bytes which should be read. If differ from the system's endianness
   *  the values will be converted
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readUint32 = function (name, count, endianness) {
    return uintReader.call(this, name, count, 4,
           endianness || this._dataEndianness);
  };

  /**
   * Read a blob and push it to the result object
   *
   * @public
   * @param {String} name Property name
   * @param {Number} count Number of bytes to be sliced from the Blob
   * @return {BlobReader} Return the target object
   */
  BlobReader.prototype.readBlob = function (name, count) {
    this._queue.push({
      count: count,
      type: BlobReader.BLOB,
      cb: function (result) {
        this._currentResult[name] = result;
      }.bind(this)
    });
    return this;
  };

  /**
   * Skips defined amount of bytes, usually used for padding
   *
   * @public
   * @param {Numner} count Number of bytes to be skipped
   * @return {BlobReader} Retnr the target object
   */
  BlobReader.prototype.skip = function (count) {
    count = count || 1;
    this._queue.push({
      count: count,
      type: BlobReader.BLOB,
      cb: function () {}
    });
    return this;
  };

  /**
   * Gets the result object
   *
   * @public
   * @return {Object} The object resulted from the calls of readUint
   */
  BlobReader.prototype.commit = function (cb) {
    if (!this._currentResult) {
      throw new Error('Cannot commit without any reads');
    }
    var res = this._currentResult;
    var task = {
      count: 0,
      type: BlobReader.BLOB,
      cb: function () {
        cb(res);
        this._currentResult = null;
      }.bind(this)
    };
    this._queue.push(task);
    return this;
  };

  w.BlobReader = BlobReader;

}(window));
<|endoftext|>