<commit_before>const React = require('react');
const ReactDOM = require('react-dom');
const Radium = require('radium');

const Icon = require('./Icon');

const StyleConstants = require('../constants/Style');

const isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i).test(navigator.userAgent);

const Select = React.createClass({
  propTypes: {
    dropdownStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    onChange: React.PropTypes.func,
    options: React.PropTypes.array,
    optionsStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    optionStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    placeholderText: React.PropTypes.string,
    scrimStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    selected: React.PropTypes.object,
    selectedStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    valid: React.PropTypes.bool
  },

  getDefaultProps () {
    return {
      onChange () {},
      options: [],
      placeholderText: 'Select One',
      selected: false,
      valid: true
    };
  },

  getInitialState () {
    return {
      highlightedValue: null,
      isOpen: false,
      selected: false,
      hoverItem: null
    };
  },

  getBackgroundColor (option) {
    if(option.value === this.state.hoverItem) {
      return {
        backgroundColor: StyleConstants.Colors.PRIMARY,
        color: StyleConstants.Colors.WHITE
      }
    }
  },

  _handleScrimClick () {
    this.setState({
      isOpen: false,
      highlightedValue: null
    });
  },

  _handleClick () {
    if (!isMobile) {
      this.setState({
        isOpen: !this.state.isOpen
      });
    }
  },

  _handleOptionClick (option) {
    this.setState({
      selected: option,
      isOpen: false,
      highlightedValue: option
    });

    this.props.onChange(option);
  },

  _handleOptionMouseOver (option) {
    this.setState({
      hoverItem: option.value
    })
  },

  _handleSelectChange (e) {
    const selectedOption = this.props.options.filter(option => {
      return option.value + '' === e.target.value;
    })[0];

    this._handleOptionClick(selectedOption);
  },

  _handleInputKeyDown (e) {
    const highlightedValue = this.state.highlightedValue;

    if (e.keyCode === 13 && highlightedValue) {
      this._handleOptionClick(highlightedValue);
    }

    if (e.keyCode === 40) {
      e.preventDefault();

      const nextIndex = this.props.options.indexOf(highlightedValue) + 1;

      if (nextIndex < this.props.options.length) {
        this.setState({
          highlightedValue: this.props.options[nextIndex]
        });

        this._scrollListDown(nextIndex);
      }
    }

    if (e.keyCode === 38) {
      e.preventDefault();

      const previousIndex = this.props.options.indexOf(highlightedValue) - 1;

      if (previousIndex > -1) {
        this.setState({
          highlightedValue: this.props.options[previousIndex]
        });

        this._scrollListUp(previousIndex);
      }
    }
  },

  _scrollListDown (nextIndex) {
    const ul = ReactDOM.findDOMNode(this.refs.optionList);
    const activeLi = ul.children[nextIndex];
    const heightFromTop = nextIndex * activeLi.clientHeight;

    if (heightFromTop > ul.clientHeight) {
      ul.scrollTop = activeLi.offsetTop - activeLi.clientHeight;
    }
  },

  _scrollListUp (prevIndex) {
    const ul = ReactDOM.findDOMNode(this.refs.optionList);
    const activeLi = ul.children[prevIndex];
    const heightFromBottom = (this.props.options.length - prevIndex) * activeLi.clientHeight;

    if (heightFromBottom > ul.clientHeight) {
      ul.scrollTop = activeLi.offsetTop - activeLi.clientHeight;
    }
  },

  _renderScrim () {
    if (this.state.isOpen) {
      return (

      );
    } else {
      return null;
    }
  },

  _renderOptions () {
    if (this.state.isOpen) {
      if (this.props.children) {
        return (

            {this.props.children}

        );
      } else {
        return (

            {this.props.options.map(option => {
              return (
                <li
                  className='mx-select-option'
                  key={option.displayValue + option.value}
                  onClick={this._handleOptionClick.bind(null, option)}
                  onMouseOver={this._handleOptionMouseOver.bind(null, option)}
                  ref={option.displayValue + option.value}
                  style={[
                    styles.option,
                    this.props.optionStyle,
                    option === this.state.highlightedValue && styles.activeItem,
                    this.getBackgroundColor(option)
                  ]}
                >
                {option.displayValue}

              );
            })}

        );
      }
    } else {
      return null;
    }
  },

  render () {
    const selected = this.state.selected || this.props.selected || { displayValue: this.props.placeholderText, value: '' };

    return (

          {this._renderScrim()}

            {selected.displayValue}
            <Icon
              size='20'
              style={styles.caret}
              type={this.state.isOpen ? 'caret-up' : 'caret-down'}
            />

          {this.props.options.length || this.props.children ? this._renderOptions() : null}

        {isMobile ? (
          <select className='mx-select-default' onChange={this._handleSelectChange} ref='defaultSelect' style={styles.select} value={selected.value}>
            {this.props.options.map(option => {
              return (<option key={option.displayValue + option.value} value={option.value}>{option.displayValue}</option>);
            })}
          </select>
        ) : null }

    );
  }
});

const styles = {
  caret: {
    color: '#CCCCCC',
    cursor: 'pointer',
    position: 'absolute',
    right: '-5px',
    top: '50%',
    transform: 'translateY(-50%)'
  },
  component: {
    backgroundColor: '#FFFFFF',
    borderRadius: '3px',
    border: '1px solid #E5E5E5',
    cursor: 'pointer',
    fontFamily: StyleConstants.FontFamily,
    fontSize: StyleConstants.FontSizes.MEDIUM,
    padding: '11px 10px 12px',
    position: 'relative',
    appearance: 'none',
    WebkitAppearance: 'none',
    boxSizing: 'border-box',
    outline: 'none'
  },
  select: {
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    width: '100%',
    WebkitAppearance: 'none',
    opacity: 0
  },
  selected: {
    position: 'relative'
  },
  activeItem: {
    backgroundColor: StyleConstants.Colors.PRIMARY,
    color: StyleConstants.Colors.WHITE
  },
  invalid: {
    borderColor: StyleConstants.Colors.STRAWBERRY
  },
  options: {
    backgroundColor: '#FFFFFF',
    border: '1px solid #E5E5E5',
    borderRadius: '0 0 3px 3px',
    left: '-1px',
    right: '-1px',
    margin: '10px 0 0 0',
    padding: '0',
    minWidth: '100%',
    position: 'absolute',
    zIndex: 10,
    fontSize: '12px',
    boxShadow: '0 30px 30px 10px rgba(0,0,0,0.1)',
    boxSizing: 'border-box',
    maxHeight: '260px',
    overflow: 'auto'
  },
  option: {
    cursor: 'pointer',
    backgroundColor: '#FFFFFF',
    padding: '10px',
    whiteSpace: 'nowrap'
  },
  scrim: {
    position: 'fixed',
    zIndex: 9,
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  }
};

module.exports = Radium(Select);
<commit_msg>fixed linting errors<commit_after>const React = require('react');
const ReactDOM = require('react-dom');
const Radium = require('radium');

const Icon = require('./Icon');

const StyleConstants = require('../constants/Style');

const isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i).test(navigator.userAgent);

const Select = React.createClass({
  propTypes: {
    dropdownStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    onChange: React.PropTypes.func,
    options: React.PropTypes.array,
    optionsStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    optionStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    placeholderText: React.PropTypes.string,
    scrimStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    selected: React.PropTypes.object,
    selectedStyle: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),
    valid: React.PropTypes.bool
  },

  getDefaultProps () {
    return {
      onChange () {},
      options: [],
      placeholderText: 'Select One',
      selected: false,
      valid: true
    };
  },

  getInitialState () {
    return {
      highlightedValue: null,
      isOpen: false,
      selected: false,
      hoverItem: null
    };
  },

  getBackgroundColor (option) {
    if (option.value === this.state.hoverItem) {
      return {
        backgroundColor: StyleConstants.Colors.PRIMARY,
        color: StyleConstants.Colors.WHITE
      };
    } else {
      return null;
    }
  },

  _handleScrimClick () {
    this.setState({
      isOpen: false,
      highlightedValue: null
    });
  },

  _handleClick () {
    if (!isMobile) {
      this.setState({
        isOpen: !this.state.isOpen
      });
    }
  },

  _handleOptionClick (option) {
    this.setState({
      selected: option,
      isOpen: false,
      highlightedValue: option
    });

    this.props.onChange(option);
  },

  _handleOptionMouseOver (option) {
    this.setState({
      hoverItem: option.value
    });
  },

  _handleSelectChange (e) {
    const selectedOption = this.props.options.filter(option => {
      return option.value + '' === e.target.value;
    })[0];

    this._handleOptionClick(selectedOption);
  },

  _handleInputKeyDown (e) {
    const highlightedValue = this.state.highlightedValue;

    if (e.keyCode === 13 && highlightedValue) {
      this._handleOptionClick(highlightedValue);
    }

    if (e.keyCode === 40) {
      e.preventDefault();

      const nextIndex = this.props.options.indexOf(highlightedValue) + 1;

      if (nextIndex < this.props.options.length) {
        this.setState({
          highlightedValue: this.props.options[nextIndex]
        });

        this._scrollListDown(nextIndex);
      }
    }

    if (e.keyCode === 38) {
      e.preventDefault();

      const previousIndex = this.props.options.indexOf(highlightedValue) - 1;

      if (previousIndex > -1) {
        this.setState({
          highlightedValue: this.props.options[previousIndex]
        });

        this._scrollListUp(previousIndex);
      }
    }
  },

  _scrollListDown (nextIndex) {
    const ul = ReactDOM.findDOMNode(this.refs.optionList);
    const activeLi = ul.children[nextIndex];
    const heightFromTop = nextIndex * activeLi.clientHeight;

    if (heightFromTop > ul.clientHeight) {
      ul.scrollTop = activeLi.offsetTop - activeLi.clientHeight;
    }
  },

  _scrollListUp (prevIndex) {
    const ul = ReactDOM.findDOMNode(this.refs.optionList);
    const activeLi = ul.children[prevIndex];
    const heightFromBottom = (this.props.options.length - prevIndex) * activeLi.clientHeight;

    if (heightFromBottom > ul.clientHeight) {
      ul.scrollTop = activeLi.offsetTop - activeLi.clientHeight;
    }
  },

  _renderScrim () {
    if (this.state.isOpen) {
      return (

      );
    } else {
      return null;
    }
  },

  _renderOptions () {
    if (this.state.isOpen) {
      if (this.props.children) {
        return (

            {this.props.children}

        );
      } else {
        return (

            {this.props.options.map(option => {
              return (
                <li
                  className='mx-select-option'
                  key={option.displayValue + option.value}
                  onClick={this._handleOptionClick.bind(null, option)}
                  onMouseOver={this._handleOptionMouseOver.bind(null, option)}
                  ref={option.displayValue + option.value}
                  style={[
                    styles.option,
                    this.props.optionStyle,
                    option === this.state.highlightedValue && styles.activeItem,
                    this.getBackgroundColor(option)
                  ]}
                >
                {option.displayValue}

              );
            })}

        );
      }
    } else {
      return null;
    }
  },

  render () {
    const selected = this.state.selected || this.props.selected || { displayValue: this.props.placeholderText, value: '' };

    return (

          {this._renderScrim()}

            {selected.displayValue}
            <Icon
              size='20'
              style={styles.caret}
              type={this.state.isOpen ? 'caret-up' : 'caret-down'}
            />

          {this.props.options.length || this.props.children ? this._renderOptions() : null}

        {isMobile ? (
          <select className='mx-select-default' onChange={this._handleSelectChange} ref='defaultSelect' style={styles.select} value={selected.value}>
            {this.props.options.map(option => {
              return (<option key={option.displayValue + option.value} value={option.value}>{option.displayValue}</option>);
            })}
          </select>
        ) : null }

    );
  }
});

const styles = {
  caret: {
    color: '#CCCCCC',
    cursor: 'pointer',
    position: 'absolute',
    right: '-5px',
    top: '50%',
    transform: 'translateY(-50%)'
  },
  component: {
    backgroundColor: '#FFFFFF',
    borderRadius: '3px',
    border: '1px solid #E5E5E5',
    cursor: 'pointer',
    fontFamily: StyleConstants.FontFamily,
    fontSize: StyleConstants.FontSizes.MEDIUM,
    padding: '11px 10px 12px',
    position: 'relative',
    appearance: 'none',
    WebkitAppearance: 'none',
    boxSizing: 'border-box',
    outline: 'none'
  },
  select: {
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    width: '100%',
    WebkitAppearance: 'none',
    opacity: 0
  },
  selected: {
    position: 'relative'
  },
  activeItem: {
    backgroundColor: StyleConstants.Colors.PRIMARY,
    color: StyleConstants.Colors.WHITE
  },
  invalid: {
    borderColor: StyleConstants.Colors.STRAWBERRY
  },
  options: {
    backgroundColor: '#FFFFFF',
    border: '1px solid #E5E5E5',
    borderRadius: '0 0 3px 3px',
    left: '-1px',
    right: '-1px',
    margin: '10px 0 0 0',
    padding: '0',
    minWidth: '100%',
    position: 'absolute',
    zIndex: 10,
    fontSize: '12px',
    boxShadow: '0 30px 30px 10px rgba(0,0,0,0.1)',
    boxSizing: 'border-box',
    maxHeight: '260px',
    overflow: 'auto'
  },
  option: {
    cursor: 'pointer',
    backgroundColor: '#FFFFFF',
    padding: '10px',
    whiteSpace: 'nowrap'
  },
  scrim: {
    position: 'fixed',
    zIndex: 9,
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  }
};

module.exports = Radium(Select);
<|endoftext|>


<commit_before>import React from 'react';
import { Navbar, Nav, NavItem, Row, Col, Grid, Image, Thumbnail, Button, Jumbotron, Well } from 'react-bootstrap';
import { NavbarHeader, NavbarToggle, NavbarCollapse, NavbarBrand } from 'react-bootstrap/lib/NavbarHeader';
import { LinkContainer } from 'react-router-bootstrap';
import { Router, Route, browserHistory, IndexRoute, Link } from 'react-router';
import { inject, observer } from 'mobx-react';
import { render } from 'react-dom';
import { Card, CardBlock, CardTitle, CardDeck, CardText, CardSubtitle, CardHeader, CardColumns, CardImg, Form, FormGroup, FormText, Input, Label, FormFeedback, ClassName, Modal, ModalHeader, ModalBody, ModalFooter, ButtonLabel } from "reactstrap";

class Account extends React.Component {
  constructor() {
    super();
    this.state = {
      category: "",
      description: "",
      condition: "",
      url: ""
    };
    this.handleCategoryChange = this.handleCategoryChange.bind(this);
    this.handleDescriptionChange = this.handleDescriptionChange.bind(this);
    this.handleConditionChange = this.handleConditionChange.bind(this);
    this.handleUrlChange = this.handleUrlChange.bind(this);
    this.handleNewItem = this.handleNewItem.bind(this);
  }

  handleCategoryChange(e) {
    this.setState({category: e.target.value});
  }

  handleDescriptionChange(e) {
    this.setState({description: e.target.value});
  }

  handleConditionChange(e) {
    this.setState({condition: e.target.value});
  }
  handleUrlChange(e) {
    this.setState({url: e.target.value});
  }

  handleNewItem(event) {
    event.preventDefault();
    this.props.itemStore.newItem(this.state);
  }

  render() {
    return(

        Welcome {this.props.userStore.name}!

          <Navbar inverse collapseOnSelect>
            <Navbar.Header>
              <Navbar.Brand>
                <Link to="/"/>
              </Navbar.Brand>
              <Navbar.Toggle/>
            </Navbar.Header>
            <Navbar.Collapse>

                <LinkContainer to={{pathname: '/'}}><NavItem>Main</NavItem></LinkContainer>
                <LinkContainer to={{pathname: '/Activity'}}><NavItem>Activity</NavItem></LinkContainer>
                {/*<LinkContainer to={{pathname: '/MyNeighbors'}}><NavItem>My Neighbors</NavItem></LinkContainer>*/}
                <LinkContainer to={{pathname: '/Account'}}><NavItem>Your Account!</NavItem></LinkContainer>

            </Navbar.Collapse>
          </Navbar>
          {this.props.children}

        <CardDeck>
          <Card>
            <CardImg top width="100%" src="http://cdn.playbuzz.com/cdn/cd6e17b1-162e-43cd-9f9d-ebe1c3401cb5/8189758a-afad-4250-9582-f81713f31366.jpg" alt="Card image cap" />
            <CardBlock>
              <CardTitle>Alex</CardTitle>
              <CardSubtitle>Bozeman, Montana</CardSubtitle>
              <CardText>Just a hard-working dude that has equipment Im happy to lend and hoping to borrow a few things for side projects.</CardText>
              <Button>Edit Profile</Button>
              <Button>Edit Items</Button>
            </CardBlock>
          </Card>
        </CardDeck>

      <form method="" role="form">
        <Col sm={8}>
          <legend>Add Your Items!!</legend>

            <input onChange={this.handleCategoryChange} value={this.state.category} className="form-control" id="category" placeholder="category"/>

            <input onChange={this.handleDescriptionChange} value={this.state.description} className="form-control" id="description" placeholder="description"/>

            <input onChange={this.handleConditionChange} value={this.state.condition} className="form-control" id="condition" placeholder="condition"/>

            <input onChange={this.handleUrlChange} value={this.state.url} className="form-control" id="url" placeholder="url"/>

          <button onClick={this.handleNewItem} type="submit" className="btn btn-primary">Add Your Item!</button>
          </Col>
          </form>

    );
  }
}

Account.propTypes = {
  children: React.PropTypes.object,
  newItem: React.PropTypes.func,
  itemStore: React.PropTypes.object,
  userStore: React.PropTypes.object
};

export default inject ('itemStore', 'userStore')(observer(Account));
<commit_msg>working card account<commit_after>import React from 'react';
import { Navbar, Nav, NavItem, Row, Col, Grid, Image, Thumbnail, Button, Jumbotron, Well } from 'react-bootstrap';
import { NavbarHeader, NavbarToggle, NavbarCollapse, NavbarBrand } from 'react-bootstrap/lib/NavbarHeader';
import { LinkContainer } from 'react-router-bootstrap';
import { Router, Route, browserHistory, IndexRoute, Link } from 'react-router';
import { inject, observer } from 'mobx-react';
import { render } from 'react-dom';
import { Card, CardBlock, CardTitle, CardDeck, CardText, CardSubtitle, CardHeader, CardColumns, CardImg, Form, FormGroup, FormText, Input, Label, FormFeedback, ClassName, Modal, ModalHeader, ModalBody, ModalFooter, ButtonLabel } from "reactstrap";

class Account extends React.Component {
  constructor() {
    super();
    this.state = {
      category: "",
      description: "",
      condition: "",
      url: ""
    };
    this.handleCategoryChange = this.handleCategoryChange.bind(this);
    this.handleDescriptionChange = this.handleDescriptionChange.bind(this);
    this.handleConditionChange = this.handleConditionChange.bind(this);
    this.handleUrlChange = this.handleUrlChange.bind(this);
    this.handleNewItem = this.handleNewItem.bind(this);
  }

  handleCategoryChange(e) {
    this.setState({category: e.target.value});
  }

  handleDescriptionChange(e) {
    this.setState({description: e.target.value});
  }

  handleConditionChange(e) {
    this.setState({condition: e.target.value});
  }
  handleUrlChange(e) {
    this.setState({url: e.target.value});
  }

  handleNewItem(event) {
    event.preventDefault();
    this.props.itemStore.newItem(this.state);
  }

  render() {
    return(

        Welcome {this.props.userStore.name}!

          <Navbar inverse collapseOnSelect>
            <Navbar.Header>
              <Navbar.Brand>
                <Link to="/"/>
              </Navbar.Brand>
              <Navbar.Toggle/>
            </Navbar.Header>
            <Navbar.Collapse>

                <LinkContainer to={{pathname: '/'}}><NavItem>Main</NavItem></LinkContainer>
                <LinkContainer to={{pathname: '/Activity'}}><NavItem>Activity</NavItem></LinkContainer>
                {/*<LinkContainer to={{pathname: '/MyNeighbors'}}><NavItem>My Neighbors</NavItem></LinkContainer>*/}
                <LinkContainer to={{pathname: '/Account'}}><NavItem>Your Account!</NavItem></LinkContainer>

            </Navbar.Collapse>
          </Navbar>
          {this.props.children}

      <Jumbotron>
      <CardColumns>
        <Card block>
          <CardImg top width="100%" src="https://www.colourbox.com/preview/4613991-funny-redhead-guy.jpg" rounded alt="Card image cap" />
          <Card block inverse style={{ backgroundColor: '#333', borderColor: '#333', width: '100%'}}>
            <CardTitle>Alex</CardTitle>
            <CardSubtitle>Bozeman, Montana</CardSubtitle>
            <CardText>Just a hard-working dude that has equipment Im happy to lend and hoping to borrow a few things for side projects.</CardText>
            <Button>Edit Profile</Button>
            <Button>Edit Items</Button>
          </Card>
        </Card>
        </CardColumns>
        </Jumbotron>

      <form method="" role="form">
        <Col sm={8}>
          <legend>Add Your Items!!</legend>

            <input onChange={this.handleCategoryChange} value={this.state.category} className="form-control" id="category" placeholder="category"/>

            <input onChange={this.handleDescriptionChange} value={this.state.description} className="form-control" id="description" placeholder="description"/>

            <input onChange={this.handleConditionChange} value={this.state.condition} className="form-control" id="condition" placeholder="condition"/>

            <input onChange={this.handleUrlChange} value={this.state.url} className="form-control" id="url" placeholder="url"/>

          <button onClick={this.handleNewItem} type="submit" className="btn btn-primary">Add Your Item!</button>
          </Col>
          </form>

    );
  }
}

Account.propTypes = {
  children: React.PropTypes.object,
  newItem: React.PropTypes.func,
  itemStore: React.PropTypes.object,
  userStore: React.PropTypes.object
};

export default inject ('itemStore', 'userStore')(observer(Account));
<|endoftext|>


<commit_before>const mockIstanbulTracker = babel => {
  const { types: t } = babel

  return {
    visitor: {
      Program(path) {
        debugger
      },
      Identifier(path) {
        if (path.node.name.indexOf('cov_') !== -1) {
          path.node.name = 'cov_tracker'
        }
      }
    }
  }
}

runTests(
  __dirname,
  [],
  ['babel-plugin-istanbul', 'babel-plugin-macros', mockIstanbulTracker],
  transform => {
    const { code } = transform()
    expect(code).toMatch(
      "const name = (cov_tracker.s[0]++, `Xin chào ${'Vinh'} 👻`);"
    )
    expect(code).toMatch(
      'return success ? (cov_tracker.b[1][0]++, `Xin chào ${name} 👻`) : (cov_tracker.b[1][1]++, "it\'s an error");'
    )
    expect(code).toMatch(
      'cov_tracker.f[0]++;\n  cov_tracker.s[2]++;\n  return t`Xin chào ${name} 👻`;'
    )
  }
)
<commit_msg>Remove debug code<commit_after>const mockIstanbulTracker = babel => {
  const { types: t } = babel

  return {
    visitor: {
      Identifier(path) {
        if (path.node.name.indexOf('cov_') !== -1) {
          path.node.name = 'cov_tracker'
        }
      }
    }
  }
}

runTests(
  __dirname,
  [],
  ['babel-plugin-istanbul', 'babel-plugin-macros', mockIstanbulTracker],
  transform => {
    const { code } = transform()
    expect(code).toMatch(
      "const name = (cov_tracker.s[0]++, `Xin chào ${'Vinh'} 👻`);"
    )
    expect(code).toMatch(
      'return success ? (cov_tracker.b[1][0]++, `Xin chào ${name} 👻`) : (cov_tracker.b[1][1]++, "it\'s an error");'
    )
    expect(code).toMatch(
      'cov_tracker.f[0]++;\n  cov_tracker.s[2]++;\n  return t`Xin chào ${name} 👻`;'
    )
  }
)
<|endoftext|>


<commit_before>var chimneypot = require('./index.js');

// Empty constructor
shouldThrowError(function() {
  new chimneypot();
});

// No port
shouldThrowError(function() {
  new chimneypot({
    path: '/',
    secret: 'spooky'
  });
});

// No path
shouldThrowError(function() {
  new chimneypot({
    port: 1996,
    secret: 'spooky'
  });
});

// No secret
shouldThrowError(function() {
  new chimneypot({
    port: 1996,
    path: '/'
  });
});

// Non numeric port
(function() {
  // String port
  shouldThrowError(function() {
    new chimneypot({
      port: 'wrong',
      path: '/',
      secret: 'spooky'
    });
  });

  // Boolean port (false)
  shouldThrowError(function() {
    new chimneypot({
      port: false,
      path: '/',
      secret: 'spooky'
    });
  });

  // Boolean port (true)
  shouldThrowError(function() {
    new chimneypot({
      port: true,
      path: '/',
      secret: 'spooky'
    });
  });

  // Array port
  shouldThrowError(function() {
    new chimneypot({
      port: [],
      path: '/',
      secret: 'spooky'
    });
  });

  // Object port
  shouldThrowError(function() {
    new chimneypot({
      port: {},
      path: '/',
      secret: 'spooky'
    });
  });

  // Non-integer port
  shouldThrowError(function() {
    new chimneypot({
      port: 50.5,
      path: '/',
      secret: 'spooky'
    });
  });
})();

// listen() errors
(function() {
  var c = _setupValidChimneypot();

  shouldThrowError(function() {
    c.listen();
  });

  c.route('push', function(){});

  shouldNotThrowError(function() {
    c.listen();
  });

  c.kill();
})();

console.log("all tests passed");

function shouldThrowError(func) {
  if (!_throws(func)) {
    throw new Error("Expected error to be thrown, but was not thrown");
  }
}

function shouldNotThrowError(func) {
  if (_throws(func)) {
    throw new Error("Expected error to not be thrown, but was thrown");
  }
}

function _setupValidChimneypot() {
  return new chimneypot({
    port: 1996,
    path: '/',
    secret: 'spooky'
  });
}

function _throws(func) {
  try {
    func();
  } catch (err) {
    return true;
  }
  return false;
}
<commit_msg>Log errors<commit_after>var chimneypot = require('./index.js');

// Empty constructor
shouldThrowError(function() {
  new chimneypot();
});

// No port
shouldThrowError(function() {
  new chimneypot({
    path: '/',
    secret: 'spooky'
  });
});

// No path
shouldThrowError(function() {
  new chimneypot({
    port: 1996,
    secret: 'spooky'
  });
});

// No secret
shouldThrowError(function() {
  new chimneypot({
    port: 1996,
    path: '/'
  });
});

// Non numeric port
(function() {
  // String port
  shouldThrowError(function() {
    new chimneypot({
      port: 'wrong',
      path: '/',
      secret: 'spooky'
    });
  });

  // Boolean port (false)
  shouldThrowError(function() {
    new chimneypot({
      port: false,
      path: '/',
      secret: 'spooky'
    });
  });

  // Boolean port (true)
  shouldThrowError(function() {
    new chimneypot({
      port: true,
      path: '/',
      secret: 'spooky'
    });
  });

  // Array port
  shouldThrowError(function() {
    new chimneypot({
      port: [],
      path: '/',
      secret: 'spooky'
    });
  });

  // Object port
  shouldThrowError(function() {
    new chimneypot({
      port: {},
      path: '/',
      secret: 'spooky'
    });
  });

  // Non-integer port
  shouldThrowError(function() {
    new chimneypot({
      port: 50.5,
      path: '/',
      secret: 'spooky'
    });
  });
})();

// listen() errors
(function() {
  var c = _setupValidChimneypot();

  shouldThrowError(function() {
    c.listen();
  });

  c.route('push', function(){});

  shouldNotThrowError(function() {
    c.listen();
  });

  c.kill();
})();

console.log("all tests passed");

function shouldThrowError(func) {
  if (!_throws(func)) {
    throw new Error("Expected error to be thrown, but was not thrown");
  }
}

function shouldNotThrowError(func) {
  if (_throws(func)) {
    throw new Error("Expected error to not be thrown, but was thrown");
  }
}

function _setupValidChimneypot() {
  return new chimneypot({
    port: 1996,
    path: '/',
    secret: 'spooky'
  });
}

function _throws(func) {
  try {
    func();
  } catch (err) {
    console.log(err);

    return true;
  }
  return false;
}
<|endoftext|>


<commit_before>var registerComponent = require('../core/component').registerComponent;
var THREE = require('../lib/three');
var utils = require('../utils/');

var checkHeadsetConnected = utils.checkHeadsetConnected;

/**
 * Camera component.
 * Pairs along with camera system to handle tracking the active camera.
 */
module.exports.Component = registerComponent('camera', {
  schema: {
    active: { default: true },
    far: { default: 10000 },
    fov: { default: 80, min: 0 },
    near: { default: 0.005, min: 0 },
    userHeight: { default: 0, min: 0 },
    zoom: { default: 1, min: 0 }
  },

  /**
   * Initialize three.js camera and add it to the entity.
   * Add reference from scene to this entity as the camera.
   */
  init: function () {
    var camera = this.camera = new THREE.PerspectiveCamera();
    var sceneEl = this.el.sceneEl;
    this.el.setObject3D('camera', camera);
    this.bindMethods();
    sceneEl.addEventListener('enter-vr', this.removeHeightOffset);
    sceneEl.addEventListener('enter-vr', this.saveCameraPose);
    sceneEl.addEventListener('exit-vr', this.restoreCameraPose);
    sceneEl.addEventListener('exit-vr', this.addHeightOffset);
  },

  bindMethods: function () {
    this.addHeightOffset = this.addHeightOffset.bind(this);
    this.removeHeightOffset = this.removeHeightOffset.bind(this);
    this.updateHeightOffset = this.updateHeightOffset.bind(this);
    this.saveCameraPose = this.saveCameraPose.bind(this);
    this.restoreCameraPose = this.restoreCameraPose.bind(this);
  },

  /**
   * Offsets the position of the camera to set a human scale perspective
   * This offset is not necessary when using a headset because the SDK
   * will return the real user's head height and position.
   */
  addHeightOffset: function () {
    var el = this.el;
    var currentPosition;
    // Only applies if there's a default camera with no applied offset.
    if (this.userHeightOffset) { return; }
    currentPosition = el.getComputedAttribute('position') || {x: 0, y: 0, z: 0};
    this.userHeightOffset = this.data.userHeight;
    el.setAttribute('position', {
      x: currentPosition.x,
      y: currentPosition.y + this.userHeightOffset,
      z: currentPosition.z
    });
  },

  /**
   * Remove the height offset (called when entering VR) since WebVR API gives absolute
   * position.
   * Does not apply for mobile.
   */
  removeHeightOffset: function () {
    var currentPosition;
    var el = this.el;
    var headsetConnected;
    var sceneEl = el.sceneEl;
    var userHeightOffset = this.userHeightOffset;

    // Checking this.headsetConnected to make the value injectable for unit tests.
    headsetConnected = this.headsetConnected || checkHeadsetConnected();

    // If there's not a headset connected we keep the offset.
    // Necessary for fullscreen mode with no headset.
    if (sceneEl.isMobile || !userHeightOffset || !headsetConnected) { return; }

    this.userHeightOffset = undefined;
    currentPosition = el.getAttribute('position') || {x: 0, y: 0, z: 0};
    el.setAttribute('position', {
      x: currentPosition.x,
      y: currentPosition.y - userHeightOffset,
      z: currentPosition.z
    });
  },

  /**
   * Enables updating camera.userHeight
   */
  updateHeightOffset: function () {
    var currentPosition;
    var headsetConnected;
    var el = this.el;
    var oldHeightOffset = this.userHeightOffset;

    headsetConnected = this.headsetConnected || checkHeadsetConnected();

    // Do not update camera.userHeight if headset is connected
    if (headsetConnected) { return; }

    this.userHeightOffset = this.data.userHeight;

    currentPosition = el.getComputedAttribute('position') || {x: 0, y: 0, z: 0};
    el.setAttribute('position', {
      x: currentPosition.x,
      y: currentPosition.y - oldHeightOffset + this.userHeightOffset,
      z: currentPosition.z
    });
  },

  saveCameraPose: function () {
    var el = this.el;
    var headsetConnected = this.headsetConnected || checkHeadsetConnected();
    if (this.savedPose || !headsetConnected) { return; }
    this.savedPose = {
      position: el.getAttribute('position'),
      rotation: el.getAttribute('rotation')
    };
  },

  restoreCameraPose: function () {
    var el = this.el;
    var savedPose = this.savedPose;
    if (!savedPose) { return; }
    // Resets camera orientation
    el.setAttribute('position', savedPose.position);
    el.setAttribute('rotation', savedPose.rotation);
    this.savedPose = undefined;
  },

  /**
   * Remove camera on remove (callback).
   */
  remove: function () {
    var sceneEl = this.el.sceneEl;
    this.el.removeObject3D('camera');
    sceneEl.removeEventListener('enter-vr', this.removeHeightOffset);
    sceneEl.removeEventListener('enter-vr', this.saveCameraPose);
    sceneEl.removeEventListener('exit-vr', this.restoreCameraPose);
    sceneEl.removeEventListener('exit-vr', this.addHeightOffset);
  },

  /**
   * Update three.js camera.
   */
  update: function (oldData) {
    var el = this.el;
    var data = this.data;
    var camera = this.camera;
    var system = this.system;
    if (!oldData || oldData.userHeight !== data.userHeight) {
      this.userHeightOffset = oldData.userHeight || 0;
      this.updateHeightOffset();
    }

    // Update properties.
    camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
    camera.far = data.far;
    camera.fov = data.fov;
    camera.near = data.near;
    camera.zoom = data.zoom;
    camera.updateProjectionMatrix();

    // Active property did not change.
    if (oldData && oldData.active === data.active) { return; }

    // If `active` property changes, or first update, handle active camera with system.
    if (data.active && system.activeCameraEl !== this.el) {
      // Camera enabled. Set camera to this camera.
      system.setActiveCamera(el);
    } else if (!data.active && system.activeCameraEl === this.el) {
      // Camera disabled. Set camera to another camera.
      system.disableActiveCamera();
    }
  }
});
<commit_msg>camera.js style nits (#1755)<commit_after>var registerComponent = require('../core/component').registerComponent;
var THREE = require('../lib/three');
var utils = require('../utils/');

var checkHeadsetConnected = utils.checkHeadsetConnected;

/**
 * Camera component.
 * Pairs along with camera system to handle tracking the active camera.
 */
module.exports.Component = registerComponent('camera', {
  schema: {
    active: {default: true},
    far: {default: 10000},
    fov: {default: 80, min: 0},
    near: {default: 0.005, min: 0},
    userHeight: {default: 0, min: 0},
    zoom: {default: 1, min: 0}
  },

  /**
   * Initialize three.js camera and add it to the entity.
   * Add reference from scene to this entity as the camera.
   */
  init: function () {
    var camera = this.camera = new THREE.PerspectiveCamera();
    var sceneEl = this.el.sceneEl;
    this.el.setObject3D('camera', camera);
    this.bindMethods();
    sceneEl.addEventListener('enter-vr', this.removeHeightOffset);
    sceneEl.addEventListener('enter-vr', this.saveCameraPose);
    sceneEl.addEventListener('exit-vr', this.restoreCameraPose);
    sceneEl.addEventListener('exit-vr', this.addHeightOffset);
  },

  bindMethods: function () {
    this.addHeightOffset = this.addHeightOffset.bind(this);
    this.removeHeightOffset = this.removeHeightOffset.bind(this);
    this.updateHeightOffset = this.updateHeightOffset.bind(this);
    this.saveCameraPose = this.saveCameraPose.bind(this);
    this.restoreCameraPose = this.restoreCameraPose.bind(this);
  },

  /**
   * Update three.js camera.
   */
  update: function (oldData) {
    var el = this.el;
    var data = this.data;
    var camera = this.camera;
    var system = this.system;

    // Update height offset.
    if (!oldData || oldData.userHeight !== data.userHeight) {
      this.userHeightOffset = oldData.userHeight || 0;
      this.updateHeightOffset();
    }

    // Update properties.
    camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
    camera.far = data.far;
    camera.fov = data.fov;
    camera.near = data.near;
    camera.zoom = data.zoom;
    camera.updateProjectionMatrix();

    // Active property did not change.
    if (oldData && oldData.active === data.active) { return; }

    // If `active` property changes, or first update, handle active camera with system.
    if (data.active && system.activeCameraEl !== el) {
      // Camera enabled. Set camera to this camera.
      system.setActiveCamera(el);
    } else if (!data.active && system.activeCameraEl === el) {
      // Camera disabled. Set camera to another camera.
      system.disableActiveCamera();
    }
  },

  /**
   * Remove camera on remove (callback).
   */
  remove: function () {
    var sceneEl = this.el.sceneEl;
    this.el.removeObject3D('camera');
    sceneEl.removeEventListener('enter-vr', this.removeHeightOffset);
    sceneEl.removeEventListener('enter-vr', this.saveCameraPose);
    sceneEl.removeEventListener('exit-vr', this.restoreCameraPose);
    sceneEl.removeEventListener('exit-vr', this.addHeightOffset);
  },

  /**
   * Offsets the position of the camera to set a human scale perspective
   * This offset is not necessary when using a headset because the SDK
   * will return the real user's head height and position.
   */
  addHeightOffset: function () {
    var el = this.el;
    var currentPosition;

    // Only applies if there's a default camera with no applied offset.
    if (this.userHeightOffset) { return; }

    this.userHeightOffset = this.data.userHeight;

    currentPosition = el.getComputedAttribute('position') || {x: 0, y: 0, z: 0};
    el.setAttribute('position', {
      x: currentPosition.x,
      y: currentPosition.y + this.userHeightOffset,
      z: currentPosition.z
    });
  },

  /**
   * Remove the height offset (called when entering VR) since WebVR API gives absolute
   * position.
   * Does not apply for mobile.
   */
  removeHeightOffset: function () {
    var currentPosition;
    var el = this.el;
    var headsetConnected;
    var sceneEl = el.sceneEl;
    var userHeightOffset = this.userHeightOffset;

    // If there's not a headset connected we keep the offset.
    // Necessary for fullscreen mode with no headset.
    // Checking this.headsetConnected to make the value injectable for unit tests.
    headsetConnected = this.headsetConnected || checkHeadsetConnected();
    if (sceneEl.isMobile || !userHeightOffset || !headsetConnected) { return; }

    this.userHeightOffset = undefined;
    currentPosition = el.getAttribute('position') || {x: 0, y: 0, z: 0};
    el.setAttribute('position', {
      x: currentPosition.x,
      y: currentPosition.y - userHeightOffset,
      z: currentPosition.z
    });
  },

  /**
   * Enables updating camera.userHeight
   */
  updateHeightOffset: function () {
    var currentPosition;
    var headsetConnected;
    var el = this.el;
    var oldHeightOffset = this.userHeightOffset;

    // Do not update camera.userHeight if headset is connected
    headsetConnected = this.headsetConnected || checkHeadsetConnected();
    if (headsetConnected) { return; }

    this.userHeightOffset = this.data.userHeight;

    currentPosition = el.getComputedAttribute('position') || {x: 0, y: 0, z: 0};
    el.setAttribute('position', {
      x: currentPosition.x,
      y: currentPosition.y - oldHeightOffset + this.userHeightOffset,
      z: currentPosition.z
    });
  },

  /**
   * Save camera pose before entering VR to restore later if exiting.
   */
  saveCameraPose: function () {
    var el = this.el;
    var headsetConnected = this.headsetConnected || checkHeadsetConnected();

    if (this.savedPose || !headsetConnected) { return; }

    this.savedPose = {
      position: el.getAttribute('position'),
      rotation: el.getAttribute('rotation')
    };
  },

  /**
   * Reset camera pose to before entering VR.
   */
  restoreCameraPose: function () {
    var el = this.el;
    var savedPose = this.savedPose;

    if (!savedPose) { return; }

    // Reset camera orientation.
    el.setAttribute('position', savedPose.position);
    el.setAttribute('rotation', savedPose.rotation);
    this.savedPose = undefined;
  }
});
<|endoftext|>


<commit_before>const logging = require('@tryghost/logging');
const _ = require('lodash');

module.exports = class RouterController {
    /**
     * RouterController
     *
     * @param {object} deps
     * @param {any} deps.offersAPI
     * @param {any} deps.paymentsService
     * @param {any} deps.productRepository
     * @param {any} deps.memberRepository
     * @param {any} deps.StripePrice
     * @param {() => boolean} deps.allowSelfSignup
     * @param {any} deps.magicLinkService
     * @param {import('@tryghost/members-stripe-service')} deps.stripeAPIService
     * @param {any} deps.tokenService
     * @param {{isSet(name: string): boolean}} deps.labsService
     * @param {any} deps.config
     */
    constructor({
        offersAPI,
        paymentsService,
        productRepository,
        memberRepository,
        StripePrice,
        allowSelfSignup,
        magicLinkService,
        stripeAPIService,
        tokenService,
        sendEmailWithMagicLink,
        labsService,
        config
    }) {
        this._offersAPI = offersAPI;
        this._paymentsService = paymentsService;
        this._productRepository = productRepository;
        this._memberRepository = memberRepository;
        this._StripePrice = StripePrice;
        this._allowSelfSignup = allowSelfSignup;
        this._magicLinkService = magicLinkService;
        this._stripeAPIService = stripeAPIService;
        this._tokenService = tokenService;
        this._sendEmailWithMagicLink = sendEmailWithMagicLink;
        this.labsService = labsService;
        this._config = config;
    }

    async ensureStripe(_req, res, next) {
        if (!this._stripeAPIService.configured) {
            res.writeHead(400);
            return res.end('Stripe not configured');
        }
        try {
            await this._stripeAPIService.ready();
            next();
        } catch (err) {
            res.writeHead(500);
            return res.end('There was an error configuring stripe');
        }
    }

    async createCheckoutSetupSession(req, res) {
        const identity = req.body.identity;

        if (!identity) {
            res.writeHead(400);
            return res.end();
        }

        let email;
        try {
            if (!identity) {
                email = null;
            } else {
                const claims = await this._tokenService.decodeToken(identity);
                email = claims && claims.sub;
            }
        } catch (err) {
            res.writeHead(401);
            return res.end('Unauthorized');
        }

        const member = email ? await this._memberRepository.get({email}) : null;

        if (!member) {
            res.writeHead(403);
            return res.end('Bad Request.');
        }

        let customer;
        if (!req.body.subscription_id) {
            customer = await this._stripeAPIService.getCustomerForMemberCheckoutSession(member);
        } else {
            const subscriptions = await member.related('stripeSubscriptions').fetch();
            const subscription = subscriptions.models.find((sub) => {
                return sub.get('subscription_id') === req.body.subscription_id;
            });

            if (!subscription) {
                res.writeHead(404);
                res.end(`Could not find subscription ${req.body.subscription_id}`);
            }
            customer = await this._stripeAPIService.getCustomer(subscription.get('customer_id'));
        }

        const session = await this._stripeAPIService.createCheckoutSetupSession(customer, {
            successUrl: req.body.successUrl || this._config.billingSuccessUrl,
            cancelUrl: req.body.cancelUrl || this._config.billingCancelUrl,
            subscription_id: req.body.subscription_id
        });
        const publicKey = this._stripeAPIService.getPublicKey();
        const sessionInfo = {
            sessionId: session.id,
            publicKey
        };
        res.writeHead(200, {
            'Content-Type': 'application/json'
        });

        res.end(JSON.stringify(sessionInfo));
    }

    async createCheckoutSession(req, res) {
        let ghostPriceId = req.body.priceId;
        const identity = req.body.identity;
        const offerId = req.body.offerId;
        const metadata = req.body.metadata;

        if (!ghostPriceId && !offerId) {
            res.writeHead(400);
            return res.end('Bad Request.');
        }

        if (offerId && ghostPriceId) {
            res.writeHead(400);
            return res.end('Bad Request.');
        }

        let couponId = null;
        if (offerId) {
            try {
                const offer = await this._offersAPI.getOffer({id: offerId});
                const tier = (await this._productRepository.get(offer.tier)).toJSON();

                if (offer.status === 'archived') {
                    res.writeHead(403);
                    return res.end('Offer is archived.');
                }

                if (offer.cadence === 'month') {
                    ghostPriceId = tier.monthly_price_id;
                } else {
                    ghostPriceId = tier.yearly_price_id;
                }

                const coupon = await this._paymentsService.getCouponForOffer(offerId);
                couponId = coupon.id;

                metadata.offer = offer.id;
            } catch (err) {
                res.writeHead(500);
                return res.end('Could not use Offer.');
            }
        }

        const price = await this._StripePrice.findOne({
            id: ghostPriceId
        });

        if (!price) {
            res.writeHead(404);
            return res.end('Not Found.');
        }

        const priceId = price.get('stripe_price_id');

        let email;
        try {
            if (!identity) {
                email = null;
            } else {
                const claims = await this._tokenService.decodeToken(identity);
                email = claims && claims.sub;
            }
        } catch (err) {
            res.writeHead(401);
            return res.end('Unauthorized');
        }

        const member = email ? await this._memberRepository.get({email}, {withRelated: ['stripeCustomers', 'products']}) : null;

        let successUrl = req.body.successUrl || this._config.checkoutSuccessUrl;
        let cancelUrl = req.body.cancelUrl || this._config.checkoutCancelUrl;

        if (!member && req.body.customerEmail && !req.body.successUrl) {
            const memberExistsForCustomer = await this._memberRepository.get({email: req.body.customerEmail});
            if (!memberExistsForCustomer) {
                successUrl = await this._magicLinkService.getMagicLink({
                    tokenData: {
                        email: req.body.customerEmail
                    },
                    type: 'signup'
                });
            }
        }

        if (!member) {
            const customer = null;
            const session = await this._stripeAPIService.createCheckoutSession(priceId, customer, {
                coupon: couponId,
                successUrl,
                cancelUrl,
                customerEmail: req.body.customerEmail,
                metadata: metadata
            });
            const publicKey = this._stripeAPIService.getPublicKey();

            const sessionInfo = {
                publicKey,
                sessionId: session.id
            };

            res.writeHead(200, {
                'Content-Type': 'application/json'
            });

            return res.end(JSON.stringify(sessionInfo));
        }

        if (member.related('products').length !== 0) {
            res.writeHead(403);
            return res.end('No permission');
        }

        let stripeCustomer;

        for (const customer of member.related('stripeCustomers').models) {
            try {
                const fetchedCustomer = await this._stripeAPIService.getCustomer(customer.get('customer_id'));
                if (!fetchedCustomer.deleted) {
                    stripeCustomer = fetchedCustomer;
                    break;
                }
            } catch (err) {
                logging.info('Ignoring error for fetching customer for checkout');
            }
        }

        if (!stripeCustomer) {
            stripeCustomer = await this._stripeAPIService.createCustomer({email: member.get('email')});
        }

        try {
            const session = await this._stripeAPIService.createCheckoutSession(priceId, stripeCustomer, {
                coupon: couponId,
                successUrl,
                cancelUrl,
                metadata: metadata
            });
            const publicKey = this._stripeAPIService.getPublicKey();

            const sessionInfo = {
                publicKey,
                sessionId: session.id
            };

            res.writeHead(200, {
                'Content-Type': 'application/json'
            });

            return res.end(JSON.stringify(sessionInfo));
        } catch (e) {
            const error = e.message || 'Unable to initiate checkout session';
            res.writeHead(400);
            return res.end(error);
        }
    }

    async sendMagicLink(req, res) {
        const {email, emailType, requestSrc} = req.body;
        if (!email) {
            res.writeHead(400);
            return res.end('Bad Request.');
        }

        try {
            if (!this._allowSelfSignup()) {
                const member = await this._memberRepository.get({email});
                if (member) {
                    const tokenData = {};
                    await this._sendEmailWithMagicLink({email, tokenData, requestedType: emailType, requestSrc});
                }
            } else {
                const tokenData = _.pick(req.body, ['labels', 'name']);
                await this._sendEmailWithMagicLink({email, tokenData, requestedType: emailType, requestSrc});
            }
            res.writeHead(201);
            return res.end('Created.');
        } catch (err) {
            if (err.code === 'EENVELOPE') {
                logging.error(err);
                res.writeHead(400);
                return res.end('Bad Request.');
            }
            const statusCode = (err && err.statusCode) || 500;
            logging.error(err);
            res.writeHead(statusCode);
            return res.end('Internal Server Error.');
        }
    }
};
<commit_msg>Restricted signing up with archived Tiers<commit_after>const logging = require('@tryghost/logging');
const _ = require('lodash');

module.exports = class RouterController {
    /**
     * RouterController
     *
     * @param {object} deps
     * @param {any} deps.offersAPI
     * @param {any} deps.paymentsService
     * @param {any} deps.productRepository
     * @param {any} deps.memberRepository
     * @param {any} deps.StripePrice
     * @param {() => boolean} deps.allowSelfSignup
     * @param {any} deps.magicLinkService
     * @param {import('@tryghost/members-stripe-service')} deps.stripeAPIService
     * @param {any} deps.tokenService
     * @param {{isSet(name: string): boolean}} deps.labsService
     * @param {any} deps.config
     */
    constructor({
        offersAPI,
        paymentsService,
        productRepository,
        memberRepository,
        StripePrice,
        allowSelfSignup,
        magicLinkService,
        stripeAPIService,
        tokenService,
        sendEmailWithMagicLink,
        labsService,
        config
    }) {
        this._offersAPI = offersAPI;
        this._paymentsService = paymentsService;
        this._productRepository = productRepository;
        this._memberRepository = memberRepository;
        this._StripePrice = StripePrice;
        this._allowSelfSignup = allowSelfSignup;
        this._magicLinkService = magicLinkService;
        this._stripeAPIService = stripeAPIService;
        this._tokenService = tokenService;
        this._sendEmailWithMagicLink = sendEmailWithMagicLink;
        this.labsService = labsService;
        this._config = config;
    }

    async ensureStripe(_req, res, next) {
        if (!this._stripeAPIService.configured) {
            res.writeHead(400);
            return res.end('Stripe not configured');
        }
        try {
            await this._stripeAPIService.ready();
            next();
        } catch (err) {
            res.writeHead(500);
            return res.end('There was an error configuring stripe');
        }
    }

    async createCheckoutSetupSession(req, res) {
        const identity = req.body.identity;

        if (!identity) {
            res.writeHead(400);
            return res.end();
        }

        let email;
        try {
            if (!identity) {
                email = null;
            } else {
                const claims = await this._tokenService.decodeToken(identity);
                email = claims && claims.sub;
            }
        } catch (err) {
            res.writeHead(401);
            return res.end('Unauthorized');
        }

        const member = email ? await this._memberRepository.get({email}) : null;

        if (!member) {
            res.writeHead(403);
            return res.end('Bad Request.');
        }

        let customer;
        if (!req.body.subscription_id) {
            customer = await this._stripeAPIService.getCustomerForMemberCheckoutSession(member);
        } else {
            const subscriptions = await member.related('stripeSubscriptions').fetch();
            const subscription = subscriptions.models.find((sub) => {
                return sub.get('subscription_id') === req.body.subscription_id;
            });

            if (!subscription) {
                res.writeHead(404);
                res.end(`Could not find subscription ${req.body.subscription_id}`);
            }
            customer = await this._stripeAPIService.getCustomer(subscription.get('customer_id'));
        }

        const session = await this._stripeAPIService.createCheckoutSetupSession(customer, {
            successUrl: req.body.successUrl || this._config.billingSuccessUrl,
            cancelUrl: req.body.cancelUrl || this._config.billingCancelUrl,
            subscription_id: req.body.subscription_id
        });
        const publicKey = this._stripeAPIService.getPublicKey();
        const sessionInfo = {
            sessionId: session.id,
            publicKey
        };
        res.writeHead(200, {
            'Content-Type': 'application/json'
        });

        res.end(JSON.stringify(sessionInfo));
    }

    async createCheckoutSession(req, res) {
        let ghostPriceId = req.body.priceId;
        const identity = req.body.identity;
        const offerId = req.body.offerId;
        const metadata = req.body.metadata;

        if (!ghostPriceId && !offerId) {
            res.writeHead(400);
            return res.end('Bad Request.');
        }

        if (offerId && ghostPriceId) {
            res.writeHead(400);
            return res.end('Bad Request.');
        }

        let couponId = null;
        if (offerId) {
            try {
                const offer = await this._offersAPI.getOffer({id: offerId});
                const tier = (await this._productRepository.get(offer.tier)).toJSON();

                if (offer.status === 'archived') {
                    res.writeHead(403);
                    return res.end('Offer is archived.');
                }

                if (offer.cadence === 'month') {
                    ghostPriceId = tier.monthly_price_id;
                } else {
                    ghostPriceId = tier.yearly_price_id;
                }

                const coupon = await this._paymentsService.getCouponForOffer(offerId);
                couponId = coupon.id;

                metadata.offer = offer.id;
            } catch (err) {
                res.writeHead(500);
                return res.end('Could not use Offer.');
            }
        }

        const price = await this._StripePrice.findOne({
            id: ghostPriceId
        });

        if (!price) {
            res.writeHead(404);
            return res.end('Not Found.');
        }

        const priceId = price.get('stripe_price_id');

        const product = await this._productRepository.get({stripe_price_id: priceId});

        if (product.get('active') !== true) {
            res.writeHead(403);
            return res.end('Tier is archived.');
        }

        let email;
        try {
            if (!identity) {
                email = null;
            } else {
                const claims = await this._tokenService.decodeToken(identity);
                email = claims && claims.sub;
            }
        } catch (err) {
            res.writeHead(401);
            return res.end('Unauthorized');
        }

        const member = email ? await this._memberRepository.get({email}, {withRelated: ['stripeCustomers', 'products']}) : null;

        let successUrl = req.body.successUrl || this._config.checkoutSuccessUrl;
        let cancelUrl = req.body.cancelUrl || this._config.checkoutCancelUrl;

        if (!member && req.body.customerEmail && !req.body.successUrl) {
            const memberExistsForCustomer = await this._memberRepository.get({email: req.body.customerEmail});
            if (!memberExistsForCustomer) {
                successUrl = await this._magicLinkService.getMagicLink({
                    tokenData: {
                        email: req.body.customerEmail
                    },
                    type: 'signup'
                });
            }
        }

        if (!member) {
            const customer = null;
            const session = await this._stripeAPIService.createCheckoutSession(priceId, customer, {
                coupon: couponId,
                successUrl,
                cancelUrl,
                customerEmail: req.body.customerEmail,
                metadata: metadata
            });
            const publicKey = this._stripeAPIService.getPublicKey();

            const sessionInfo = {
                publicKey,
                sessionId: session.id
            };

            res.writeHead(200, {
                'Content-Type': 'application/json'
            });

            return res.end(JSON.stringify(sessionInfo));
        }

        if (member.related('products').length !== 0) {
            res.writeHead(403);
            return res.end('No permission');
        }

        let stripeCustomer;

        for (const customer of member.related('stripeCustomers').models) {
            try {
                const fetchedCustomer = await this._stripeAPIService.getCustomer(customer.get('customer_id'));
                if (!fetchedCustomer.deleted) {
                    stripeCustomer = fetchedCustomer;
                    break;
                }
            } catch (err) {
                logging.info('Ignoring error for fetching customer for checkout');
            }
        }

        if (!stripeCustomer) {
            stripeCustomer = await this._stripeAPIService.createCustomer({email: member.get('email')});
        }

        try {
            const session = await this._stripeAPIService.createCheckoutSession(priceId, stripeCustomer, {
                coupon: couponId,
                successUrl,
                cancelUrl,
                metadata: metadata
            });
            const publicKey = this._stripeAPIService.getPublicKey();

            const sessionInfo = {
                publicKey,
                sessionId: session.id
            };

            res.writeHead(200, {
                'Content-Type': 'application/json'
            });

            return res.end(JSON.stringify(sessionInfo));
        } catch (e) {
            const error = e.message || 'Unable to initiate checkout session';
            res.writeHead(400);
            return res.end(error);
        }
    }

    async sendMagicLink(req, res) {
        const {email, emailType, requestSrc} = req.body;
        if (!email) {
            res.writeHead(400);
            return res.end('Bad Request.');
        }

        try {
            if (!this._allowSelfSignup()) {
                const member = await this._memberRepository.get({email});
                if (member) {
                    const tokenData = {};
                    await this._sendEmailWithMagicLink({email, tokenData, requestedType: emailType, requestSrc});
                }
            } else {
                const tokenData = _.pick(req.body, ['labels', 'name']);
                await this._sendEmailWithMagicLink({email, tokenData, requestedType: emailType, requestSrc});
            }
            res.writeHead(201);
            return res.end('Created.');
        } catch (err) {
            if (err.code === 'EENVELOPE') {
                logging.error(err);
                res.writeHead(400);
                return res.end('Bad Request.');
            }
            const statusCode = (err && err.statusCode) || 500;
            logging.error(err);
            res.writeHead(statusCode);
            return res.end('Internal Server Error.');
        }
    }
};
<|endoftext|>


<commit_before>var p = Proxy.create({
  get: function(proxy, name) {
    console.log('read request to ' + name + ' property');
    if (name=="test_test")
       return 1234;
    else
       return "Meh";
  },
  set: function(proxy, name, value) {
    console.log('write request to ' + name + ' property with ' + value + ' value');
  }
});

console.log(p.test_test);
console.log(p.test)
p.qqq = "test";<commit_msg>removed test.js<commit_after><|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100, white: true, plusplus: true, eqeq: true */
/*global require, exports */

////////////////////////////////////////////////////////////////////////////////
/// @brief statistics handler
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler, Lucas Dohmen
/// @author Copyright 2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var internal = require("internal");

// -----------------------------------------------------------------------------
// --SECTION--                                  module "org/arangodb/statistics"
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief reloads the user authentication data
////////////////////////////////////////////////////////////////////////////////

exports.historian = function (param) {
  "use strict";

  try {
    var result = {};

    result.time = internal.time();
    result.system = internal.processStatistics();
    result.client = internal.clientStatistics();
    result.http = internal.httpStatistics();
    result.server = internal.serverStatistics();

    internal.db._statistics.save(result);
  }
  catch (err) {
  }
};

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\|/\\*jslint"
// End:
<commit_msg>added clusterId in statistics<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100, white: true, plusplus: true, eqeq: true */
/*global require, exports */

////////////////////////////////////////////////////////////////////////////////
/// @brief statistics handler
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler, Lucas Dohmen
/// @author Copyright 2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var internal = require("internal");
var cluster = require("org/arangodb/cluster");

// -----------------------------------------------------------------------------
// --SECTION--                                  module "org/arangodb/statistics"
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief cluster id or undefined for standalone
////////////////////////////////////////////////////////////////////////////////

var clusterId;

if (cluster.isCluster()) {
  clusterId = ArangoServerState.id();
}

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief reloads the user authentication data
////////////////////////////////////////////////////////////////////////////////

exports.historian = function (param) {
  "use strict";

  try {
    var result = {};

    result.time = internal.time();
    result.system = internal.processStatistics();
    result.client = internal.clientStatistics();
    result.http = internal.httpStatistics();
    result.server = internal.serverStatistics();

    if (clusterId !== undefined) {
      result.clusterId = clusterId;
    }

    internal.db._statistics.save(result);
  }
  catch (err) {
  }
};

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\|/\\*jslint"
// End:
<|endoftext|>


<commit_before>import React, { createRef, PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { COLOR, COLORS, TINTS } from '../../constants';
import theme from './theme.css';

const overflows = ['auto', 'hidden', 'scroll', 'visible'];
const spacings = [0, 1, 2, 3, 4, 5, 6, 7, 8];

const borderRadiuses = {
  square: null,
  circle: '50%',
  rounded: '4px',
};

class Box extends PureComponent {
  boxNode = createRef();

  getBorder = value => {
    const { borderColor, borderTint } = this.props;
    return `${value}px solid ${COLOR[borderColor.toUpperCase()][borderTint.toUpperCase()]}`;
  };

  render() {
    const {
      alignContent,
      alignItems,
      alignSelf,
      backgroundColor,
      backgroundTint,
      borderBottomWidth,
      borderColor,
      borderLeftWidth,
      borderRightWidth,
      borderTint,
      borderTopWidth,
      borderWidth,
      borderRadius,
      borderTopLeftRadius = borderRadius,
      borderTopRightRadius = borderRadius,
      borderBottomLeftRadius = borderRadius,
      borderBottomRightRadius = borderRadius,
      boxSizing,
      children,
      className,
      display,
      element,
      flex,
      flexBasis,
      flexDirection,
      flexGrow,
      flexShrink,
      flexWrap,
      justifyContent,
      margin,
      marginHorizontal = margin,
      marginVertical = margin,
      marginBottom = marginVertical,
      marginLeft = marginHorizontal,
      marginRight = marginHorizontal,
      marginTop = marginVertical,
      order,
      overflow,
      overflowX,
      overflowY,
      padding,
      paddingHorizontal = padding,
      paddingVertical = padding,
      paddingBottom = paddingVertical,
      paddingLeft = paddingHorizontal,
      paddingRight = paddingHorizontal,
      paddingTop = paddingVertical,
      style,
      textAlign,
      ...others
    } = this.props;

    const classNames = cx(
      theme['box'],
      {
        [theme[`align-content-${alignContent}`]]: alignContent,
        [theme[`align-items-${alignItems}`]]: alignItems,
        [theme[`align-self-${alignSelf}`]]: alignSelf,
        [theme[`background-color-${backgroundColor}-${backgroundTint}`]]: backgroundColor && backgroundTint,
        [theme[`background-color-${backgroundColor}`]]:
          backgroundColor && (!backgroundTint || backgroundTint === 'normal'),
        [theme[`display-${display}`]]: display,
        [theme[`flex-direction-${flexDirection}`]]: flexDirection,
        [theme[`flex-wrap-${flexWrap}`]]: flexWrap,
        [theme[`justify-content-${justifyContent}`]]: justifyContent,
        [theme[`margin-bottom-${marginBottom}`]]: marginBottom > 0,
        [theme[`margin-left-${marginLeft}`]]: marginLeft > 0,
        [theme[`margin-right-${marginRight}`]]: marginRight > 0,
        [theme[`margin-top-${marginTop}`]]: marginTop > 0,
        [theme[`padding-bottom-${paddingBottom}`]]: paddingBottom > 0,
        [theme[`padding-left-${paddingLeft}`]]: paddingLeft > 0,
        [theme[`padding-right-${paddingRight}`]]: paddingRight > 0,
        [theme[`padding-top-${paddingTop}`]]: paddingTop > 0,
        [theme[`text-align-${textAlign}`]]: textAlign,
      },
      className,
    );

    const elementStyles = {
      ...(borderWidth && { border: this.getBorder(borderWidth) }),
      ...(borderBottomWidth && { borderBottom: this.getBorder(borderBottomWidth) }),
      ...(borderLeftWidth && { borderLeft: this.getBorder(borderLeftWidth) }),
      ...(borderRightWidth && { borderRight: this.getBorder(borderRightWidth) }),
      ...(borderTopWidth && { borderTop: this.getBorder(borderTopWidth) }),
      ...(borderRadius && { borderRadius: borderRadiuses[borderRadius] }),
      ...(borderTopLeftRadius && { borderTopLeftRadius: borderRadiuses[borderTopLeftRadius] }),
      ...(borderTopRightRadius && { borderTopRightRadius: borderRadiuses[borderTopRightRadius] }),
      ...(borderBottomLeftRadius && { borderBottomLeftRadius: borderRadiuses[borderBottomLeftRadius] }),
      ...(borderBottomRightRadius && { borderBottomRightRadius: borderRadiuses[borderBottomRightRadius] }),
      ...(boxSizing && { boxSizing }),
      ...(flex && { flex }),
      ...(flexBasis && { flexBasis }),
      ...(!isNaN(flexGrow) ? { flexGrow } : {}),
      ...(!isNaN(flexShrink) ? { flexShrink } : {}),
      ...(!isNaN(order) ? { order } : {}),
      ...(overflow && { overflow }),
      ...(overflowX && { overflowX }),
      ...(overflowY && { overflowY }),
      ...style,
    };

    const Element = element;

    return (
      <Element ref={this.boxNode} className={classNames} style={elementStyles} {...others}>
        {children}
      </Element>
    );
  }
}

Box.propTypes = {
  alignContent: PropTypes.oneOf(['center', 'flex-start', 'flex-end', 'space-around', 'space-between', 'space-evenly']),
  alignItems: PropTypes.oneOf(['center', 'flex-start', 'flex-end', 'baseline', 'stretch']),
  alignSelf: PropTypes.oneOf(['center', 'flex-start', 'flex-end', 'stretch']),
  backgroundColor: PropTypes.oneOf(COLORS),
  backgroundTint: PropTypes.oneOf(TINTS),
  borderBottomWidth: PropTypes.number,
  borderColor: PropTypes.oneOf(COLORS),
  borderLeftWidth: PropTypes.number,
  borderRightWidth: PropTypes.number,
  borderTint: PropTypes.oneOf(TINTS),
  borderTopWidth: PropTypes.number,
  borderWidth: PropTypes.number,
  borderRadius: PropTypes.oneOf(Object.keys(borderRadiuses)),
  borderTopLeftRadius: PropTypes.oneOf(Object.keys(borderRadiuses)),
  borderTopRightRadius: PropTypes.oneOf(Object.keys(borderRadiuses)),
  borderBottomLeftRadius: PropTypes.oneOf(Object.keys(borderRadiuses)),
  borderBottomRightRadius: PropTypes.oneOf(Object.keys(borderRadiuses)),
  boxSizing: PropTypes.oneOf(['border-box', 'content-box']),
  children: PropTypes.any,
  className: PropTypes.string,
  display: PropTypes.oneOf(['inline', 'inline-block', 'block', 'flex', 'inline-flex']),
  element: PropTypes.node,
  flex: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  flexBasis: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  flexDirection: PropTypes.oneOf(['row', 'row-reverse', 'column', 'column-reverse']),
  flexGrow: PropTypes.number,
  flexShrink: PropTypes.number,
  flexWrap: PropTypes.oneOf(['nowrap', 'wrap', 'wrap-reverse']),
  justifyContent: PropTypes.oneOf([
    'center',
    'flex-start',
    'flex-end',
    'space-around',
    'space-between',
    'space-evenly',
  ]),
  margin: PropTypes.oneOf(spacings),
  marginHorizontal: PropTypes.oneOf(spacings),
  marginVertical: PropTypes.oneOf(spacings),
  marginBottom: PropTypes.oneOf(spacings),
  marginLeft: PropTypes.oneOf(spacings),
  marginRight: PropTypes.oneOf(spacings),
  marginTop: PropTypes.oneOf(spacings),
  order: PropTypes.number,
  overflow: PropTypes.oneOf(overflows),
  overflowX: PropTypes.oneOf(overflows),
  overflowY: PropTypes.oneOf(overflows),
  padding: PropTypes.oneOf(spacings),
  paddingHorizontal: PropTypes.oneOf(spacings),
  paddingVertical: PropTypes.oneOf(spacings),
  paddingBottom: PropTypes.oneOf(spacings),
  paddingLeft: PropTypes.oneOf(spacings),
  paddingRight: PropTypes.oneOf(spacings),
  paddingTop: PropTypes.oneOf(spacings),
  style: PropTypes.object,
  textAlign: PropTypes.oneOf(['center', 'left', 'right']),
};

Box.defaultProps = {
  borderColor: 'neutral',
  borderTint: 'dark',
  borderRadius: 'square',
  element: 'div',
  margin: 0,
  padding: 0,
};

export default Box;
<commit_msg>Split up spacings array into margins and paddings<commit_after>import React, { createRef, PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { COLOR, COLORS, TINTS } from '../../constants';
import theme from './theme.css';

const overflows = ['auto', 'hidden', 'scroll', 'visible'];
const margins = [0, 1, 2, 3, 4, 5, 6, 7, 8];
const paddings = [0, 1, 2, 3, 4, 5, 6, 7, 8];

const borderRadiuses = {
  square: null,
  circle: '50%',
  rounded: '4px',
};

class Box extends PureComponent {
  boxNode = createRef();

  getBorder = value => {
    const { borderColor, borderTint } = this.props;
    return `${value}px solid ${COLOR[borderColor.toUpperCase()][borderTint.toUpperCase()]}`;
  };

  render() {
    const {
      alignContent,
      alignItems,
      alignSelf,
      backgroundColor,
      backgroundTint,
      borderBottomWidth,
      borderColor,
      borderLeftWidth,
      borderRightWidth,
      borderTint,
      borderTopWidth,
      borderWidth,
      borderRadius,
      borderTopLeftRadius = borderRadius,
      borderTopRightRadius = borderRadius,
      borderBottomLeftRadius = borderRadius,
      borderBottomRightRadius = borderRadius,
      boxSizing,
      children,
      className,
      display,
      element,
      flex,
      flexBasis,
      flexDirection,
      flexGrow,
      flexShrink,
      flexWrap,
      justifyContent,
      margin,
      marginHorizontal = margin,
      marginVertical = margin,
      marginBottom = marginVertical,
      marginLeft = marginHorizontal,
      marginRight = marginHorizontal,
      marginTop = marginVertical,
      order,
      overflow,
      overflowX,
      overflowY,
      padding,
      paddingHorizontal = padding,
      paddingVertical = padding,
      paddingBottom = paddingVertical,
      paddingLeft = paddingHorizontal,
      paddingRight = paddingHorizontal,
      paddingTop = paddingVertical,
      style,
      textAlign,
      ...others
    } = this.props;

    const classNames = cx(
      theme['box'],
      {
        [theme[`align-content-${alignContent}`]]: alignContent,
        [theme[`align-items-${alignItems}`]]: alignItems,
        [theme[`align-self-${alignSelf}`]]: alignSelf,
        [theme[`background-color-${backgroundColor}-${backgroundTint}`]]: backgroundColor && backgroundTint,
        [theme[`background-color-${backgroundColor}`]]:
          backgroundColor && (!backgroundTint || backgroundTint === 'normal'),
        [theme[`display-${display}`]]: display,
        [theme[`flex-direction-${flexDirection}`]]: flexDirection,
        [theme[`flex-wrap-${flexWrap}`]]: flexWrap,
        [theme[`justify-content-${justifyContent}`]]: justifyContent,
        [theme[`margin-bottom-${marginBottom}`]]: marginBottom > 0,
        [theme[`margin-left-${marginLeft}`]]: marginLeft > 0,
        [theme[`margin-right-${marginRight}`]]: marginRight > 0,
        [theme[`margin-top-${marginTop}`]]: marginTop > 0,
        [theme[`padding-bottom-${paddingBottom}`]]: paddingBottom > 0,
        [theme[`padding-left-${paddingLeft}`]]: paddingLeft > 0,
        [theme[`padding-right-${paddingRight}`]]: paddingRight > 0,
        [theme[`padding-top-${paddingTop}`]]: paddingTop > 0,
        [theme[`text-align-${textAlign}`]]: textAlign,
      },
      className,
    );

    const elementStyles = {
      ...(borderWidth && { border: this.getBorder(borderWidth) }),
      ...(borderBottomWidth && { borderBottom: this.getBorder(borderBottomWidth) }),
      ...(borderLeftWidth && { borderLeft: this.getBorder(borderLeftWidth) }),
      ...(borderRightWidth && { borderRight: this.getBorder(borderRightWidth) }),
      ...(borderTopWidth && { borderTop: this.getBorder(borderTopWidth) }),
      ...(borderRadius && { borderRadius: borderRadiuses[borderRadius] }),
      ...(borderTopLeftRadius && { borderTopLeftRadius: borderRadiuses[borderTopLeftRadius] }),
      ...(borderTopRightRadius && { borderTopRightRadius: borderRadiuses[borderTopRightRadius] }),
      ...(borderBottomLeftRadius && { borderBottomLeftRadius: borderRadiuses[borderBottomLeftRadius] }),
      ...(borderBottomRightRadius && { borderBottomRightRadius: borderRadiuses[borderBottomRightRadius] }),
      ...(boxSizing && { boxSizing }),
      ...(flex && { flex }),
      ...(flexBasis && { flexBasis }),
      ...(!isNaN(flexGrow) ? { flexGrow } : {}),
      ...(!isNaN(flexShrink) ? { flexShrink } : {}),
      ...(!isNaN(order) ? { order } : {}),
      ...(overflow && { overflow }),
      ...(overflowX && { overflowX }),
      ...(overflowY && { overflowY }),
      ...style,
    };

    const Element = element;

    return (
      <Element ref={this.boxNode} className={classNames} style={elementStyles} {...others}>
        {children}
      </Element>
    );
  }
}

Box.propTypes = {
  alignContent: PropTypes.oneOf(['center', 'flex-start', 'flex-end', 'space-around', 'space-between', 'space-evenly']),
  alignItems: PropTypes.oneOf(['center', 'flex-start', 'flex-end', 'baseline', 'stretch']),
  alignSelf: PropTypes.oneOf(['center', 'flex-start', 'flex-end', 'stretch']),
  backgroundColor: PropTypes.oneOf(COLORS),
  backgroundTint: PropTypes.oneOf(TINTS),
  borderBottomWidth: PropTypes.number,
  borderColor: PropTypes.oneOf(COLORS),
  borderLeftWidth: PropTypes.number,
  borderRightWidth: PropTypes.number,
  borderTint: PropTypes.oneOf(TINTS),
  borderTopWidth: PropTypes.number,
  borderWidth: PropTypes.number,
  borderRadius: PropTypes.oneOf(Object.keys(borderRadiuses)),
  borderTopLeftRadius: PropTypes.oneOf(Object.keys(borderRadiuses)),
  borderTopRightRadius: PropTypes.oneOf(Object.keys(borderRadiuses)),
  borderBottomLeftRadius: PropTypes.oneOf(Object.keys(borderRadiuses)),
  borderBottomRightRadius: PropTypes.oneOf(Object.keys(borderRadiuses)),
  boxSizing: PropTypes.oneOf(['border-box', 'content-box']),
  children: PropTypes.any,
  className: PropTypes.string,
  display: PropTypes.oneOf(['inline', 'inline-block', 'block', 'flex', 'inline-flex']),
  element: PropTypes.node,
  flex: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  flexBasis: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  flexDirection: PropTypes.oneOf(['row', 'row-reverse', 'column', 'column-reverse']),
  flexGrow: PropTypes.number,
  flexShrink: PropTypes.number,
  flexWrap: PropTypes.oneOf(['nowrap', 'wrap', 'wrap-reverse']),
  justifyContent: PropTypes.oneOf([
    'center',
    'flex-start',
    'flex-end',
    'space-around',
    'space-between',
    'space-evenly',
  ]),
  margin: PropTypes.oneOf(margins),
  marginHorizontal: PropTypes.oneOf(margins),
  marginVertical: PropTypes.oneOf(margins),
  marginBottom: PropTypes.oneOf(margins),
  marginLeft: PropTypes.oneOf(margins),
  marginRight: PropTypes.oneOf(margins),
  marginTop: PropTypes.oneOf(margins),
  order: PropTypes.number,
  overflow: PropTypes.oneOf(overflows),
  overflowX: PropTypes.oneOf(overflows),
  overflowY: PropTypes.oneOf(overflows),
  padding: PropTypes.oneOf(paddings),
  paddingHorizontal: PropTypes.oneOf(paddings),
  paddingVertical: PropTypes.oneOf(paddings),
  paddingBottom: PropTypes.oneOf(paddings),
  paddingLeft: PropTypes.oneOf(paddings),
  paddingRight: PropTypes.oneOf(paddings),
  paddingTop: PropTypes.oneOf(paddings),
  style: PropTypes.object,
  textAlign: PropTypes.oneOf(['center', 'left', 'right']),
};

Box.defaultProps = {
  borderColor: 'neutral',
  borderTint: 'dark',
  borderRadius: 'square',
  element: 'div',
  margin: 0,
  padding: 0,
};

export default Box;
<|endoftext|>


<commit_before>export default class Home {

  render() {

    return (

            v. 0.9 beta

    )
  }
}<commit_msg>Add todo for integrating shariff.<commit_after>export default class Home {

  render() {

    return (

            RENDER WITH SHARIFF!!!!

            v. 0.9 beta

    )
  }
}<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-3 08:37:50<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>/*
 * basex-standalone
 * https://github.com/alxarch/basex-standalone
 *
 * Copyright (c) 2013 Alexandros Sigalas
 * Licensed under the MIT license.
 */

'use strict';

var _ = require('lodash')
  , Q = require('q')
  , exec = require('child_process').exec
  , f = require('util').format
  , val = function(opt){
      return _.isPlainObject(opt) ?
      _(opt)
        .map(function(value, name){
          return f('%s=%s', name, value)
        })
        .valueOf()
        .join(',')
      :
      opt
    }
  , o2a = function(obj, a){
      a = a || ''
      return _(obj).map(function(v, n) {
        return f('-%s%s=%s', a, n, val(v))
      }).valueOf()
    }
  , esc = function(str){
      // Helper function to escape double quotes in strings.
      return str.toString().replace(/"/g, '\\"')
    }
  , BaseX = function(options){
      if (this instanceof BaseX) {
          this.env = _.assign({}, BaseX.env || {}, options || {})
      }
      else{
        var basex = new BaseX();
        return basex.exec(options)
      }
    }

var defaults = {
  debug: false
, newline: false
, update: false
, whitespace: false
, run: null
, xquery: null
, commands: []
, bind: {}
}

BaseX.default_env = _.assign({}, defaults);

var default_env = {
  java: '/usr/bin/env java'
, classpath: null
, basexpath: null
, basexjar: null
}

BaseX.env = _.assign({}, default_env);

BaseX.prototype = {
  cmd: function(options){
    var opt = _.assign({}, defaults, BaseX.defaults || {}, this.defaults || {}, options || {})
      , com = (opt.commands || []).filter(_.identity).map(esc).join(';')
      , env = _.assign({}, default_env, BaseX.env || {}, this.env || {})

    return [].concat(
          env.java
        , o2a(opt.jvmargs || {}, '')
        , env.basexpath && f('-Dorg.basex.path=%s', env.basexpath)
        , (env.basexjar || env.classpath) && ['-cp', env.basexjar || env.classpath]
        , 'org.basex.BaseX'
        , opt.debug && '-d'
        , opt.newline && '-L'
        , opt.whitespace && '-w'
        , opt.update && '-u'
        , o2a(opt.bind, 'b')
        , o2a(opt.serializer, 's')
        , com && f('-c"%s"', com)
        , opt.input && f('-i%s', opt.input)
        , opt.xquery && f('-q"%s"', esc(opt.xquery).replace(/\$/g, "\\$"))
        , opt.run
        , (opt.run || com || opt.xquery) ? '' : '"()"'
      ).filter(_.identity).join(' ')
  }
, exec: function(options){
    var def = Q.defer();

    exec(this.cmd(options), function(error, stdout, stderr){
      if(error) def.reject(error)
      def.resolve(stdout, stderr)
    })

    return def.promise
  }
}

module.exports = BaseX
<commit_msg>Export escape as a helper.<commit_after>/*
 * basex-standalone
 * https://github.com/alxarch/basex-standalone
 *
 * Copyright (c) 2013 Alexandros Sigalas
 * Licensed under the MIT license.
 */

'use strict';

var _ = require('lodash')
  , Q = require('q')
  , exec = require('child_process').exec
  , f = require('util').format
  , val = function(opt){
      return _.isPlainObject(opt) ?
      _(opt)
        .map(function(value, name){
          return f('%s=%s', name, value)
        })
        .valueOf()
        .join(',')
      :
      opt
    }
  , o2a = function(obj, a){
      a = a || ''
      return _(obj).map(function(v, n) {
        return f('-%s%s=%s', a, n, val(v))
      }).valueOf()
    }
  , esc = function(str){
      // Helper function to escape double quotes in strings.
      return str.toString().replace(/"/g, '\\"').replace(/\$/g, "\\$")
    }
  , BaseX = function(options){
      if (this instanceof BaseX) {
          this.env = _.assign({}, BaseX.env || {}, options || {})
      }
      else{
        var basex = new BaseX();
        return basex.exec(options)
      }
    }

var defaults = {
  debug: false
, newline: false
, update: false
, whitespace: false
, run: null
, xquery: null
, commands: []
, bind: {}
}

BaseX.default_env = _.assign({}, defaults);

var default_env = {
  java: '/usr/bin/env java'
, classpath: null
, basexpath: null
, basexjar: null
}

BaseX.env = _.assign({}, default_env);

// Export escape as a helper.
BaseX.helpers = {
  escape: esc
}

BaseX.prototype = {
  cmd: function(options){
    var opt = _.assign({}, defaults, BaseX.defaults || {}, this.defaults || {}, options || {})
      , com = (opt.commands || []).filter(_.identity).map(esc).join(';')
      , env = _.assign({}, default_env, BaseX.env || {}, this.env || {})

    return [].concat(
          env.java
        , o2a(opt.jvmargs || {}, '')
        , env.basexpath && f('-Dorg.basex.path=%s', env.basexpath)
        , (env.basexjar || env.classpath) && ['-cp', env.basexjar || env.classpath]
        , 'org.basex.BaseX'
        , opt.debug && '-d'
        , opt.newline && '-L'
        , opt.whitespace && '-w'
        , opt.update && '-u'
        , o2a(opt.bind, 'b')
        , o2a(opt.serializer, 's')
        , com && f('-c"%s"', com)
        , opt.input && f('-i%s', opt.input)
        , opt.xquery && f('-q"%s"', esc(opt.xquery))
        , opt.run
        , (opt.run || com || opt.xquery) ? '' : '"()"'
      ).filter(_.identity).join(' ')
  }
, exec: function(options){
    var def = Q.defer();

    exec(this.cmd(options), function(error, stdout, stderr){
      if(error) def.reject(error)
      def.resolve(stdout, stderr)
    })

    return def.promise
  }
}

module.exports = BaseX
<|endoftext|>