<commit_before>var React = require('react-native');
var Success = require('Success');
var api = require('../utils/api');

var {
    TouchableHighlight,
    Text,
    TextInput,
    StyleSheet,
    View
} = React;

class AdditionalInfo extends React.Component{
    handleSubmit(event){
      var report = this.props.report;

      this.setState({
        report: report
      });
      api.postReport(this.state.report);
      this.setState({
        report: ''
      });
    }
    render(){
        var layout = (
        <View style={styles.container}>
          <View style={styles.row}>
            <TouchableHighlight
              underlayColor={'#B1B8B9'}
              style={styles.issueButton}
              value={'aid'}
              onPress={this.handleSubmit.bind(this)}>
              <Text style={styles.issueType}>
                Aid
              </Text>
            </TouchableHighlight>
            <View style={styles.emailContainer}>
              <Text style={styles.emailLabel}>
              Email
              </Text>
              <TextInput style={styles.emailInput} />
            </View>
          </View>
          <View style={styles.row}>
            <View style={styles.locationContainer}>
              <Text style={styles.locationNameLabel}>
                Location Name
              </Text>
              <TextInput style={styles.locationNameInput} />
            </View>
          </View>
          <View style={styles.row}>
            <View style={styles.locationContainer}>
              <Text style={styles.locationAddressLabel}>
                Location Address
              </Text>
              <TextInput style={styles.locationAddressInput} />
            </View>
          </View>
          <View style={styles.row}>
            <View style={styles.policeContainer}>
              <Text style={styles.policeLabel}>
                Police Contacted
              </Text>
            </View>
            <TouchableHighlight
              underlayColor={'#B1B8B9'}
              style={styles.policeButton}
              value={false}
              onPress={this.handleSubmit.bind(this)}>
              <Text style={styles.issueType}>
                No
              </Text>
            </TouchableHighlight>
            <TouchableHighlight
              underlayColor={'#B1B8B9'}
              style={styles.policeButton}
              value={true}
              onPress={this.handleSubmit.bind(this)}>
              <Text style={styles.issueType}>
                Yes
              </Text>
            </TouchableHighlight>
          </View>
          <View style={styles.row}>
            <View style={styles.additionalNotesContainer}>
              <Text style={styles.additionalNotesLabel}>
                Additional Notes
              </Text>
              <TextInput style={styles.additionalNotesInput} />
            </View>
          </View>
          <View style={styles.row}>
            <TouchableHighlight
              underlayColor={'#B1B8B9'}
              style={styles.reportSubmitButton}
              value={true}
              onPress={this.handleSubmit.bind(this)}>
              <Text style={styles.reportSubmitButtonType}>
                Submit
              </Text>
            </TouchableHighlight>
          </View>

        </View>
        );
        return layout;
    }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 60,
  },
  row: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
    alignItems: 'center',
    marginLeft: 24,
    marginRight: 24,
    paddingTop: 24,
  },
  issueButton: {
    width: 50,
    height: 50,
    backgroundColor: '#f62745',
    padding: 8,
    borderWidth: 1,
    borderColor: '#ffffff'
  },
  issueType: {
    color: '#ffffff',
    textAlign: 'center',
    fontSize: 18,
    fontWeight: 'bold'
  },
  emailContainer: {
    marginLeft: 16
  },
  emailLabel: {
    marginTop: 16,
    marginBottom: 14,
    fontWeight: 'bold',
    fontSize: 14
  },
  emailInput: {
    width: 206,
    height: 50,
    borderColor: 'gray',
    borderWidth: 1
  },
  locationContainer:{

  },
  locationNameLabel: {
    marginTop: 16,
    marginBottom: 14,
    fontWeight: 'bold',
    fontSize: 14
  },
  locationNameInput: {
    width: 320,
    height: 50,
    borderColor: 'gray',
    borderWidth: 1
  },
  locationAddressLabel: {
    marginTop: 16,
    marginBottom: 14,
    fontWeight: 'bold',
    fontSize: 14
  },
  locationAddressInput: {
    width: 320,
    height: 50,
    borderColor: 'gray',
    borderWidth: 1
  },
  policeContainer: {

  },
  policeLabel: {
    marginTop: 16,
    marginBottom: 14,
    fontWeight: 'bold',
    fontSize: 14
  },
  policeButton: {
    width: 100,
    height: 100,
    justifyContent: 'center',
    backgroundColor: '#f62745',
    padding: 16,
    borderWidth: 1,
    borderColor: '#ffffff'
  },
  additionalNotesLabel: {
    marginTop: 16,
    marginBottom: 14,
    fontWeight: 'bold',
    fontSize: 14
  },
  additionalNotesInput: {
    width: 320,
    height: 250,
    borderColor: 'gray',
    borderWidth: 1
  },
  reportSubmitButton: {
    width: 320,
    height: 100,
    justifyContent: 'center',
    backgroundColor: '#f62745',
    padding: 16,
    borderWidth: 1,
    borderColor: '#ffffff',
    marginBottom: 48,
  },
  reportSubmitButtonType: {
    color: '#ffffff',
    textAlign: 'center',
    fontSize: 24,
    fontWeight: 'bold'
  }

});

module.exports = AdditionalInfo;<commit_msg>api to success<commit_after>var React = require('react-native');
var Success = require('./Success');
var api = require('../utils/api');

var {
    TouchableHighlight,
    Text,
    TextInput,
    StyleSheet,
    View
} = React;

class AdditionalInfo extends React.Component{
    handleSubmit(event){
      var report = this.props.report;

      this.setState({
        report: report
      });
      api.postReport(this.state.report);
      this.setState({
        report: ''
      });
    }
    render(){
        var layout = (
        <View style={styles.container}>
          <View style={styles.row}>
            <TouchableHighlight
              underlayColor={'#B1B8B9'}
              style={styles.issueButton}
              value={'aid'}
              onPress={this.handleSubmit.bind(this)}>
              <Text style={styles.issueType}>
                Aid
              </Text>
            </TouchableHighlight>
            <View style={styles.emailContainer}>
              <Text style={styles.emailLabel}>
              Email
              </Text>
              <TextInput style={styles.emailInput} />
            </View>
          </View>
          <View style={styles.row}>
            <View style={styles.locationContainer}>
              <Text style={styles.locationNameLabel}>
                Location Name
              </Text>
              <TextInput style={styles.locationNameInput} />
            </View>
          </View>
          <View style={styles.row}>
            <View style={styles.locationContainer}>
              <Text style={styles.locationAddressLabel}>
                Location Address
              </Text>
              <TextInput style={styles.locationAddressInput} />
            </View>
          </View>
          <View style={styles.row}>
            <View style={styles.policeContainer}>
              <Text style={styles.policeLabel}>
                Police Contacted
              </Text>
            </View>
            <TouchableHighlight
              underlayColor={'#B1B8B9'}
              style={styles.policeButton}
              value={false}
              onPress={this.handleSubmit.bind(this)}>
              <Text style={styles.issueType}>
                No
              </Text>
            </TouchableHighlight>
            <TouchableHighlight
              underlayColor={'#B1B8B9'}
              style={styles.policeButton}
              value={true}
              onPress={this.handleSubmit.bind(this)}>
              <Text style={styles.issueType}>
                Yes
              </Text>
            </TouchableHighlight>
          </View>
          <View style={styles.row}>
            <View style={styles.additionalNotesContainer}>
              <Text style={styles.additionalNotesLabel}>
                Additional Notes
              </Text>
              <TextInput style={styles.additionalNotesInput} />
            </View>
          </View>
          <View style={styles.row}>
            <TouchableHighlight
              underlayColor={'#B1B8B9'}
              style={styles.reportSubmitButton}
              value={true}
              onPress={this.handleSubmit.bind(this)}>
              <Text style={styles.reportSubmitButtonType}>
                Submit
              </Text>
            </TouchableHighlight>
          </View>

        </View>
        );
        return layout;
    }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 60,
  },
  row: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
    alignItems: 'center',
    marginLeft: 24,
    marginRight: 24,
    paddingTop: 24,
  },
  issueButton: {
    width: 50,
    height: 50,
    backgroundColor: '#f62745',
    padding: 8,
    borderWidth: 1,
    borderColor: '#ffffff'
  },
  issueType: {
    color: '#ffffff',
    textAlign: 'center',
    fontSize: 18,
    fontWeight: 'bold'
  },
  emailContainer: {
    marginLeft: 16
  },
  emailLabel: {
    marginTop: 16,
    marginBottom: 14,
    fontWeight: 'bold',
    fontSize: 14
  },
  emailInput: {
    width: 206,
    height: 50,
    borderColor: 'gray',
    borderWidth: 1
  },
  locationContainer:{

  },
  locationNameLabel: {
    marginTop: 16,
    marginBottom: 14,
    fontWeight: 'bold',
    fontSize: 14
  },
  locationNameInput: {
    width: 320,
    height: 50,
    borderColor: 'gray',
    borderWidth: 1
  },
  locationAddressLabel: {
    marginTop: 16,
    marginBottom: 14,
    fontWeight: 'bold',
    fontSize: 14
  },
  locationAddressInput: {
    width: 320,
    height: 50,
    borderColor: 'gray',
    borderWidth: 1
  },
  policeContainer: {

  },
  policeLabel: {
    marginTop: 16,
    marginBottom: 14,
    fontWeight: 'bold',
    fontSize: 14
  },
  policeButton: {
    width: 100,
    height: 100,
    justifyContent: 'center',
    backgroundColor: '#f62745',
    padding: 16,
    borderWidth: 1,
    borderColor: '#ffffff'
  },
  additionalNotesLabel: {
    marginTop: 16,
    marginBottom: 14,
    fontWeight: 'bold',
    fontSize: 14
  },
  additionalNotesInput: {
    width: 320,
    height: 250,
    borderColor: 'gray',
    borderWidth: 1
  },
  reportSubmitButton: {
    width: 320,
    height: 100,
    justifyContent: 'center',
    backgroundColor: '#f62745',
    padding: 16,
    borderWidth: 1,
    borderColor: '#ffffff',
    marginBottom: 48,
  },
  reportSubmitButtonType: {
    color: '#ffffff',
    textAlign: 'center',
    fontSize: 24,
    fontWeight: 'bold'
  }

});

module.exports = AdditionalInfo;<|endoftext|>


<commit_before>const Hero = class extends Phaser.Sprite {
    constructor(game, x, y, asset, frame, health, bulletSpeed) {
        super(game, x, y, asset, frame);
        this.inputEnabled = true;
        this.input.enableDrag(true);
        this.mode = 'move'
        this.anchor.x = 0.5;
        this.anchor.y = 0.5
        this.range = 300;
        this.scale.x = 0.5
        this.scale.y = 0.5

        this.fireRate = 1500;
        this.nextFire = 0;
        this.currentTarget = null;
        // this.fired = false;

        this.renderedRange = game.graphics.drawCircle(0, 0, this.range * 2);
    }

    create(){
    }

    update() {
        this.renderedRange.x = this.x;
        this.renderedRange.y = this.y;

        if (this.mode === 'move') {
            this.y -= 1;
            if (this.checkRangeForUnits(game.enemies) !== false) { this.mode = "attacking"; }
            return;
        }

        if (this.mode === 'attacking') {
            console.log("current target is ", this.currentTarget)
            this.fireAt(this.currentTarget)
        }
    }

    checkRangeForUnits(unitGroup) {
        let foundUnit = false;
        unitGroup.forEachAlive((unit) => {
            if (this.isInRange(unit)) {
                foundUnit = unit;
                this.currentTarget = foundUnit;
                // this.fireAt(unit);
            }
        })
        return foundUnit;
    }

    fireAt(unit){
        console.log("finna fire at ", unit);
        if (game.time.now > this.nextFire) {
            this.nextFire = game.time.now + this.fireRate;
            const fireball = game.fireballs.getFirstDead();
            fireball.reset(this.x, this.y);
            fireball.scale.setTo(0.03, 0.03)
            game.physics.arcade.moveToObject(fireball, unit);
        }
    }

    isInRange(unit){
        return (game.physics.arcade.distanceBetween(this, unit) < this.range + 30)
    }
}

const Enemy = class extends Phaser.Sprite {
    constructor(game, x, y, asset, frame, health, bulletSpeed) {
        super(game, x, y, asset, frame);
        this.inputEnabled = true;
        this.input.enableDrag(true);
        this.mode = '';
        this.anchor.x = 0.5;
        this.anchor.y = 0.5;
        this.scale.setTo(0.125, 0.125);
    }

    create(){
    }

    update() {
        if (this.mode === 'move') {
            this.y -= 1;
            return;
        }

        if (this.mode === 'look') {
            game.heroes.forEachAlive((hero) => {
                // console.log("I can see ", hero.x);
            })
        }

        // console.log("no mode")
    }
}

const Preload = class {
    preload() {

    }
    create() {
        this.state.start('GameState');
    }
}

const GameState = class extends Phaser.State {
    init() {
        this.thugometer = 9000
    }
    preload() {
        game.load.image('bone', 'bone.png');
        game.load.image('warrior', 'bonewarrior.png');
        game.load.image('hero', 'hero.png');
        game.load.image('fireball', 'fireball.png');
        game.stage.backgroundColor = '#182d3b';

    }
    create() {
        // game.boneSprite = createBone(game);
        // game.world.add(new BoneWarrior(game, 300, 300, 'warrior'))

        game.graphics = game.add.graphics(0,0);
        game.graphics.lineStyle(1, 0x00ff00, 1);

        game.heroes = game.add.group();
        game.enemies = game.add.group();
        game.fireballs = game.add.group();

        game.fireballs.enableBody = true;
        game.fireballs.physicsBodyType = Phaser.Physics.ARCADE;
        game.fireballs.createMultiple(50, 'fireball');
        game.fireballs.setAll('checkWorldBounds', true);
        game.fireballs.setAll('outOfBoundsKill', true);
        game.fireballs.setAll('anchor.x', 0.5);
        game.fireballs.setAll('anchor.y', 0.5);
        // game.fireballs.scale.setTo(0.03, 0.03)

        game.heroes.add(new Hero(game, 300, 800, 'hero'))
        game.enemies.add(new Enemy(game, 300, 100, 'warrior'));

    }
    render() {
        game.debug.inputInfo(32, 32);
    }
    update() {
        // game.boneSprite.y += 1;
    }
}

var game = new Phaser.Game(540, 960, Phaser.AUTO);
game.state.add('GameState', GameState, false);
game.state.start('GameState');

// const createBone = (gameObj) => {
//     const thug = () => {
//         const boneSprite = gameObj.add.sprite(220, 220, 'bone');
//         boneSprite.inputEnabled = true;
//         boneSprite.input.enableDrag(true);
//         return boneSprite
//     }
//     return thug();
// }

// game.state.add('PreloadState', Preload, false);
// function preload() {
//     game.load.image('bone', 'bone.png');
// }

// function create() {
//     game.stage.backgroundColor = '#182d3b';
//     game.boneSprite = createBoneThug(game);
// }

// function update () {
//     game.boneSprite.x += 1;
// }

// function render () {
//     game.debug.inputInfo(32, 32);
// }

// import GameState from 'states/GameState';
// import Preload from 'states/Preload';

// class Game extends Phaser.Game {

//  constructor() {
//      super(500, 500, Phaser.AUTO, 'content', null);
//      this.state.add('Preload', Preload, null);
//      this.state.add('GameState', GameState, false);
//      this.state.start('GameState');
//  }

// }

// new Game();

// import Bonethug from 'objects/bonethug';

// import GameState from 'states/GameState';
// import Preload from 'states/Preload';

// class Game extends Phaser.Game {

//  constructor() {
//      super(500, 500, Phaser.AUTO, 'content', null);
//      this.state.add('Preload', Preload, null);
//      this.state.add('GameState', GameState, false);
//      this.state.start('GameState');
//  }

// }
<commit_msg>the oysbah<commit_after>const Hero = class extends Phaser.Sprite {
    constructor(game, x, y, asset, frame, health, bulletSpeed) {
        super(game, x, y, asset, frame);
        this.inputEnabled = true;
        this.input.enableDrag(true);
        this.mode = 'move'
        this.anchor.x = 0.5;
        this.anchor.y = 0.5
        this.range = 300;
        this.scale.x = 0.5
        this.scale.y = 0.5

        this.fireRate = 1500;
        this.nextFire = 0;
        this.currentTarget = null;
        // this.fired = false;

        this.renderedRange = game.graphics.drawCircle(0, 0, this.range * 2);
    }

    create(){
    }

    update() {
        this.renderedRange.x = this.x;
        this.renderedRange.y = this.y;

        if (this.mode === 'move') {
            this.y -= 1;
            const aggroCheck = this.checkRangeForUnits(game.enemies);

            if (aggroCheck) {
                this.currentTarget = aggroCheck;
                this.mode = "attacking";
            }
        }

        if (this.mode === 'attacking') {
            this.fireAt(this.currentTarget)

            const aggroCheck = this.checkRangeForUnits(game.enemies);
            if (!aggroCheck) {
                this.mode = 'move';
            };
        }
    }

    checkRangeForUnits(unitGroup) {
        let foundUnit = false;
        unitGroup.forEachAlive((unit) => {
            if (this.isInRange(unit)) {
                foundUnit = unit;
            }
        })
        return foundUnit;
    }

    fireAt(unit){
        if (game.time.now > this.nextFire) {
            this.nextFire = game.time.now + this.fireRate;
            const fireball = game.fireballs.getFirstDead();
            fireball.reset(this.x, this.y);
            fireball.scale.setTo(0.03, 0.03)
            game.physics.arcade.moveToObject(fireball, unit);
        }
    }

    isInRange(unit){
        return (game.physics.arcade.distanceBetween(this, unit) < this.range + 30)
    }
}

const Enemy = class extends Phaser.Sprite {
    constructor(game, x, y, asset, frame, health, bulletSpeed) {
        super(game, x, y, asset, frame);
        this.inputEnabled = true;
        this.input.enableDrag(true);
        this.mode = '';
        this.anchor.x = 0.5;
        this.anchor.y = 0.5;
        this.scale.setTo(0.125, 0.125);
    }

    create(){
    }

    update() {
        if (this.mode === 'move') {
            this.y -= 1;
            return;
        }

        if (this.mode === 'look') {
            game.heroes.forEachAlive((hero) => {
                // console.log("I can see ", hero.x);
            })
        }

        // console.log("no mode")
    }
}

const Preload = class {
    preload() {

    }
    create() {
        this.state.start('GameState');
    }
}

const GameState = class extends Phaser.State {
    init() {
        this.thugometer = 9000
    }
    preload() {
        game.load.image('bone', 'bone.png');
        game.load.image('warrior', 'bonewarrior.png');
        game.load.image('hero', 'hero.png');
        game.load.image('fireball', 'fireball.png');
        game.stage.backgroundColor = '#182d3b';

    }
    create() {
        // game.boneSprite = createBone(game);
        // game.world.add(new BoneWarrior(game, 300, 300, 'warrior'))

        game.graphics = game.add.graphics(0,0);
        game.graphics.lineStyle(1, 0x00ff00, 1);

        game.heroes = game.add.group();
        game.enemies = game.add.group();
        game.fireballs = game.add.group();

        game.fireballs.enableBody = true;
        game.fireballs.physicsBodyType = Phaser.Physics.ARCADE;
        game.fireballs.createMultiple(50, 'fireball');
        game.fireballs.setAll('checkWorldBounds', true);
        game.fireballs.setAll('outOfBoundsKill', true);
        game.fireballs.setAll('anchor.x', 0.5);
        game.fireballs.setAll('anchor.y', 0.5);
        // game.fireballs.scale.setTo(0.03, 0.03)

        game.heroes.add(new Hero(game, 300, 800, 'hero'))
        game.enemies.add(new Enemy(game, 300, 100, 'warrior'));

    }
    render() {
        game.debug.inputInfo(32, 32);
    }
    update() {
        // game.boneSprite.y += 1;
    }
}

var game = new Phaser.Game(540, 960, Phaser.AUTO);
game.state.add('GameState', GameState, false);
game.state.start('GameState');

// const createBone = (gameObj) => {
//     const thug = () => {
//         const boneSprite = gameObj.add.sprite(220, 220, 'bone');
//         boneSprite.inputEnabled = true;
//         boneSprite.input.enableDrag(true);
//         return boneSprite
//     }
//     return thug();
// }

// game.state.add('PreloadState', Preload, false);
// function preload() {
//     game.load.image('bone', 'bone.png');
// }

// function create() {
//     game.stage.backgroundColor = '#182d3b';
//     game.boneSprite = createBoneThug(game);
// }

// function update () {
//     game.boneSprite.x += 1;
// }

// function render () {
//     game.debug.inputInfo(32, 32);
// }

// import GameState from 'states/GameState';
// import Preload from 'states/Preload';

// class Game extends Phaser.Game {

//  constructor() {
//      super(500, 500, Phaser.AUTO, 'content', null);
//      this.state.add('Preload', Preload, null);
//      this.state.add('GameState', GameState, false);
//      this.state.start('GameState');
//  }

// }

// new Game();

// import Bonethug from 'objects/bonethug';

// import GameState from 'states/GameState';
// import Preload from 'states/Preload';

// class Game extends Phaser.Game {

//  constructor() {
//      super(500, 500, Phaser.AUTO, 'content', null);
//      this.state.add('Preload', Preload, null);
//      this.state.add('GameState', GameState, false);
//      this.state.start('GameState');
//  }

// }
<|endoftext|>


<commit_before>const suffixes = new Map()
suffixes.set(3, 'K')
suffixes.set(6, 'M')
suffixes.set(9, 'B')
suffixes.set(12, 'T')

module.exports = (input, { precision = 2, lowercase = false } = {}) => {
  // Ensure input value is a number
  if (typeof input !== 'number') {
    throw new Error('Input value is not a number')
  }

  input = parseFloat(input)

  // Figure out how many digits in the integer
  const digits = 1 + Math.floor(Math.log10(Math.abs(input)))

  // Figure out the appropriate unit for the number
  const { suffix, zeroes } = ((num, zeroes) => {
    for (let z of suffixes.keys()) {
      if (num > z) {
        zeroes = z
      }
    }

    const suffix = suffixes.get(zeroes)

    return {
      suffix: lowercase ? suffix.toLowerCase() : suffix,
      zeroes
    }
  })(digits, null)

  const pretty = input / Math.pow(10, zeroes)

  precision = pretty % 1 === 0 ? 2 : Math.min(Math.max(1, precision), 21)

  // Return original number if less than 1K
  if (input > -1000 && input < 1000) {
    return input
  }

  return `${parseFloat(pretty.toPrecision(precision))}${suffix}`
}
<commit_msg>code cleanup<commit_after>const suffixes = new Map()
suffixes.set(3, 'K')
suffixes.set(6, 'M')
suffixes.set(9, 'B')
suffixes.set(12, 'T')

// Figure out the appropriate unit for the number
const getUnits = digits => {
  let zeroes

  for (const key of suffixes.keys()) {
    if (digits > key) {
      zeroes = key
    }
  }

  return {
    suffix: suffixes.get(zeroes),
    zeroes
  }
}

module.exports = (input, { precision = 2, lowercase = false } = {}) => {
  // Ensure input value is a number
  if (typeof input !== 'number') {
    throw new Error('Input value is not a number')
  }

  input = parseFloat(input)

  // Figure out how many digits in the integer
  const digits = 1 + Math.floor(Math.log10(Math.abs(input)))

  // Get units
  let { suffix, zeroes } = getUnits(digits)

  // Convert to lowercase if necessary
  if (lowercase) {
    suffix = suffix.toLowerCase()
  }

  const pretty = input / Math.pow(10, zeroes)

  precision = pretty % 1 === 0 ? 2 : Math.min(Math.max(1, precision), 21)

  // Return original number if less than 1K
  if (input > -1000 && input < 1000) {
    return input
  }

  return `${parseFloat(pretty.toPrecision(precision))}${suffix}`
}
<|endoftext|>


<commit_before>function trimDots(ary: string[]) {
  var i, part;
  for (i = 0; i < ary.length; ++i) {
      part = ary[i];
      if (part === '.') {
          ary.splice(i, 1);
          i -= 1;
      } else if (part === '..') {
          // If at the start, or previous value is still ..,
          // keep them so that when converted to a path it may
          // still work when converted to a path, even though
          // as an ID it is less than ideal. In larger point
          // releases, may be better to just kick out an error.
          if (i === 0 || (i == 1 && ary[2] === '..') || ary[i - 1] === '..') {
              continue;
          } else if (i > 0) {
              ary.splice(i - 1, 2);
              i -= 2;
          }
      }
  }
}

export function relativeToFile(name:string, file:string):string{
  var lastIndex,
      normalizedBaseParts,
      fileParts = (file && file.split('/')),
      nameParts = name.trim().split('/');

  if (nameParts[0].charAt(0) === '.' && fileParts) {
      //Convert file to array, and lop off the last part,
      //so that . matches that 'directory' and not name of the file's
      //module. For instance, file of 'one/two/three', maps to
      //'one/two/three.js', but we want the directory, 'one/two' for
      //this normalization.
      normalizedBaseParts = fileParts.slice(0, fileParts.length - 1);
      nameParts = normalizedBaseParts.concat(nameParts);
  }

  trimDots(nameParts);

  return nameParts.join('/');
}

export function join(path1:string, path2:string):string {
  var url1, url2, url3, i, ii, urlPrefix, trailingSlash;

  if(!path1){
    return path2;
  }

  if(!path2){
    return path1;
  }

  urlPrefix = path1.indexOf('//') === 0 ? '//' :
              path1.indexOf('/') === 0 ? '/' : '';
  trailingSlash = path2.slice(-1) == '/' ? '/' : '';

  url1 = path1.split('/');
  url2 = path2.split('/');
  url3 = [];

  for (i = 0, ii = url1.length; i < ii; ++i) {
    if (url1[i] == '..') {
      url3.pop();
    } else if (url1[i] == '.' || url1[i] == '') {
      continue;
    } else {
      url3.push(url1[i]);
    }
  }

  for (i = 0, ii = url2.length; i < ii; ++i) {
    if (url2[i] == '..') {
      url3.pop();
    } else if (url2[i] == '.' || url2[i] == '') {
      continue;
    } else {
      url3.push(url2[i]);
    }
  }

  return urlPrefix + url3.join('/').replace(/\:\//g, '://') + trailingSlash;
}

var r20 = /%20/g,
    rbracket = /\[\]$/,
    class2type = {};

'Boolean Number String Function Array Date RegExp Object Error'.split(' ').forEach((name, i) => {
  class2type['[object ' + name + ']'] = name.toLowerCase();
});

function type( obj ){
  if (obj == null){
    return obj + "";
  }

  // Support: Android<4.0 (functionish RegExp)
  return typeof obj === 'object' || typeof obj === 'function'
    ? class2type[ toString.call(obj) ] || 'object'
    : typeof obj;
}

export function buildQueryString(a:Object, traditional?:boolean):string {
  var s = [],
      add = function(key:string, value:any) {
        // If value is a function, invoke it and return its value
        value = typeof value === 'function' ? value() : (value == null ? '' : value);
        s[s.length] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
      };

  for(let prefix in a){
    _buildQueryString(prefix, a[prefix], traditional, add);
  }

  // Return the resulting serialization
  return s.join('&').replace(r20, '+');
}

function _buildQueryString(prefix:string, obj:any, traditional:boolean, add: (p:string, v:any) => void){
  if (Array.isArray(obj)){
    // Serialize array item.
    obj.forEach((v, i) => {
      if(traditional || rbracket.test(prefix)){
        // Treat each array item as a scalar.
        add(prefix, v);
      } else{
        // Item is non-scalar (array or object), encode its numeric index.
        _buildQueryString(
          prefix + '[' + (typeof v === 'object' ? i : '') + ']',
          v,
          traditional,
          add
        );
      }
    });
  } else if (!traditional && type(obj) === 'object'){
    // Serialize object item.
    for (let name in obj) {
      _buildQueryString(prefix + '[' + name + ']', obj[name], traditional, add);
    }
  } else{
    // Serialize scalar item.
    add(prefix, obj);
  }
}
<commit_msg>chore(all): formatting<commit_after>function trimDots(ary: string[]) {
  var i, part;
  for (i = 0; i < ary.length; ++i) {
      part = ary[i];
      if (part === '.') {
          ary.splice(i, 1);
          i -= 1;
      } else if (part === '..') {
          // If at the start, or previous value is still ..,
          // keep them so that when converted to a path it may
          // still work when converted to a path, even though
          // as an ID it is less than ideal. In larger point
          // releases, may be better to just kick out an error.
          if (i === 0 || (i == 1 && ary[2] === '..') || ary[i - 1] === '..') {
              continue;
          } else if (i > 0) {
              ary.splice(i - 1, 2);
              i -= 2;
          }
      }
  }
}

export function relativeToFile(name : string, file : string) : string {
  var lastIndex,
      normalizedBaseParts,
      fileParts = (file && file.split('/')),
      nameParts = name.trim().split('/');

  if (nameParts[0].charAt(0) === '.' && fileParts) {
      //Convert file to array, and lop off the last part,
      //so that . matches that 'directory' and not name of the file's
      //module. For instance, file of 'one/two/three', maps to
      //'one/two/three.js', but we want the directory, 'one/two' for
      //this normalization.
      normalizedBaseParts = fileParts.slice(0, fileParts.length - 1);
      nameParts = normalizedBaseParts.concat(nameParts);
  }

  trimDots(nameParts);

  return nameParts.join('/');
}

export function join(path1 : string, path2 : string) : string {
  var url1, url2, url3, i, ii, urlPrefix, trailingSlash;

  if(!path1){
    return path2;
  }

  if(!path2){
    return path1;
  }

  urlPrefix = path1.indexOf('//') === 0 ? '//' :
              path1.indexOf('/') === 0 ? '/' : '';
  trailingSlash = path2.slice(-1) == '/' ? '/' : '';

  url1 = path1.split('/');
  url2 = path2.split('/');
  url3 = [];

  for (i = 0, ii = url1.length; i < ii; ++i) {
    if (url1[i] == '..') {
      url3.pop();
    } else if (url1[i] == '.' || url1[i] == '') {
      continue;
    } else {
      url3.push(url1[i]);
    }
  }

  for (i = 0, ii = url2.length; i < ii; ++i) {
    if (url2[i] == '..') {
      url3.pop();
    } else if (url2[i] == '.' || url2[i] == '') {
      continue;
    } else {
      url3.push(url2[i]);
    }
  }

  return urlPrefix + url3.join('/').replace(/\:\//g, '://') + trailingSlash;
}

var r20 = /%20/g,
    rbracket = /\[\]$/,
    class2type = {};

'Boolean Number String Function Array Date RegExp Object Error'.split(' ').forEach((name, i) => {
  class2type['[object ' + name + ']'] = name.toLowerCase();
});

function type( obj ){
  if (obj == null){
    return obj + "";
  }

  // Support: Android<4.0 (functionish RegExp)
  return typeof obj === 'object' || typeof obj === 'function'
    ? class2type[ toString.call(obj) ] || 'object'
    : typeof obj;
}

export function buildQueryString(a : Object, traditional? : boolean) : string {
  var s = [],
      add = function(key:string, value:any) {
        // If value is a function, invoke it and return its value
        value = typeof value === 'function' ? value() : (value == null ? '' : value);
        s[s.length] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
      };

  for(let prefix in a){
    _buildQueryString(prefix, a[prefix], traditional, add);
  }

  // Return the resulting serialization
  return s.join('&').replace(r20, '+');
}

function _buildQueryString(prefix:string, obj:any, traditional:boolean, add: (p:string, v:any) => void){
  if (Array.isArray(obj)){
    // Serialize array item.
    obj.forEach((v, i) => {
      if(traditional || rbracket.test(prefix)){
        // Treat each array item as a scalar.
        add(prefix, v);
      } else{
        // Item is non-scalar (array or object), encode its numeric index.
        _buildQueryString(
          prefix + '[' + (typeof v === 'object' ? i : '') + ']',
          v,
          traditional,
          add
        );
      }
    });
  } else if (!traditional && type(obj) === 'object'){
    // Serialize object item.
    for (let name in obj) {
      _buildQueryString(prefix + '[' + name + ']', obj[name], traditional, add);
    }
  } else{
    // Serialize scalar item.
    add(prefix, obj);
  }
}
<|endoftext|>


<commit_before>var through = require('through2');
  gutil = require('gulp-util'),
  http = require('http'),
  https = require('https'),
  inject = require('connect-inject'),
  connect = require('connect'),
  watch = require('node-watch'),
  fs = require('fs'),
  serveIndex = require('serve-index'),
  serveStatic = require('serve-static'),
  path = require('path'),
  open = require('open'),
  enableMiddlewareShorthand = require('./enableMiddlewareShorthand'),
  socket = require('socket.io');

module.exports = function(options) {
  var defaults = {
    /**
     *
     * BASIC DEFAULTS
     *
     **/
    host: 'localhost',
    port: 8000,
    defaultFile: 'index.html',
    https: false,
    open: false,
    log: 'info',
    clientConsole: false,

    /**
     *
     * MIDDLEWARE DEFAULTS
     *
     * NOTE:
     *  All middleware should defaults should have the 'enable'
     *  property if you want to support shorthand syntax like:
     *
     *    webserver({
     *      livereload: true
     *    });
     *
     */

    // Middleware: Livereload
    livereload: {
      enable: false,
      port: 35729,
      filter: function(filename, cb) {
        cb( !(/node_modules/.test(filename)) );
      }
    },

    // Middleware: Directory listing
    // For possible options, see:
    //  https://github.com/expressjs/serve-index
    directoryListing: {
      enable: false,
      path: './',
      options: undefined
    }
  };

  // Deep extend user provided options over the all of the defaults
  // Allow shorthand syntax, using the enable property as a flag
  var config = enableMiddlewareShorthand(defaults, options, ['directoryListing', 'livereload']);

  var openInBrowser = function () {
    if (config.open === false) return;
    open('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port);
    openInBrowser = undefined;
  };

  // connect app
  var app = connect();

  //  directory listing
  if (config.directoryListing.enable) {
    app.use(serveIndex(path.resolve(config.directoryListing.path), config.directoryListing.options));
  }

  // socket.io
  if (config.livereload.enable) {
    var ioServerOrigin = 'http://' + config.host + ':' + config.livereload.port;

    // socket.io won't load if requirejs is already loaded unless I disable it first
    var snippet = "<script type=\"text/javascript\">"
      + "var ___require, ___define;"
      + "if (typeof require !== 'undefined' && typeof requirejs !== 'undefined' && require === requirejs) {"
      + "    ___require = require;"
      + "    ___define = define;"
      + "    require = define = null;"
      + "}"
      + "</script>"
      + "<script type=\"text/javascript\" src=\"" + ioServerOrigin +"/socket.io.js\"></script>"
      + "<script type=\"text/javascript\">"
      + "if (___require) { require = ___require; define = ___define }"
      + "console.log('Connecting to livereload server..." + ioServerOrigin + "');"
      + "var ___socket = io.connect('" + ioServerOrigin +"');"
      + "___socket.on('connect', function() { console.log('Successfully connected to livereload server'); });"
      + "___socket.on('connect_error', function(err) { console.log('Failed to connect to livereload server: ' + err); });"
      + "___socket.on('reload', function() { location.reload(); });"
    ;

    if (config.clientConsole) {
      // sometimes socket.io fails to serialize arguments e.g. angular $state
      // socket.io can't handle cyclic objects either
      // some browsers don't have an .apply method on console methods
      snippet += "var ___console;"
        + "if (typeof console !== 'undefined') {"
        + " ___console = console;"
        + "};"
        + "var console = {};"
        + "(function(methods) {"
        + "    var methods = ['info','log','error','warn'];"
        + "    for (var i in methods) {"
        + "        console[methods[i]] = (function(method){"
        + "            return function() {"
        + "                var args = arguments, success;"
        + "                try { args = JSON.parse(JSON.stringify(args)); success = true; } catch(e) {"
        + "                    ___console.error(e + ', console.' + method + ' will not be sent to livereload server', args);"
        + "                }"
        + "                try { if (success) ___socket.emit('console_' + method, args); } catch(e) {}"
        + "                try { if (___console[method]) ___console[method].apply(null, arguments); } catch(e) {"
        + "                     ___console[method](arguments);"
        + "                }"
        + "            }"
        + "        }(methods[i]))"
        + "    }"
        + "}())"
      ;
    }

    snippet += "</script>";

    app.use(inject({
      snippet: snippet,
      rules: [{
        match: /<\/body>/,
        fn: function(w, s) {
          return s + w;
        }
      }]
    }));

    var io = config.livereload.io = socket();
    io.serveClient(true);
    io.path("");
    io.on('connection', function(socket){
      gutil.log('Livereload client connected');

      socket.on('console_log', function(data){
        var args = [
          gutil.colors.green('log')
        ];
        for (var i in data) {
          args.push(data[i]);
        }
        gutil.log.apply(null, args);
      });
      socket.on('console_warn', function(data){
        var args = [
          gutil.colors.yellow('warn')
        ];
        for (var i in data) {
          args.push(data[i]);
        }
        gutil.log.apply(null, args);
      });
      socket.on('console_info', function(data){
        var args = [
          gutil.colors.cyan('info')
        ];
        for (var i in data) {
          args.push(data[i]);
        }
        gutil.log.apply(null, args);
      });
      socket.on('console_error', function(data){
        var args = [
          gutil.colors.red('err')
        ];
        for (var i in data) {
          args.push(data[i]);
        }
        gutil.log.apply(null, args);
      });
    });
    io.attach(
      (config.livereload.ioServer = http.Server().listen(config.livereload.port))
    );
  }

  // http server
  var webserver = null;
  if (config.https) {
    var options = {
      key: fs.readFileSync(config.https.key || __dirname + '/../ssl/dev-key.pem'),
      cert: fs.readFileSync(config.https.cert || __dirname + '/../ssl/dev-cert.pem')
    };

    webserver = https.createServer(options, app);
  }
  else {
    webserver = http.createServer(app);
  }

  // Create server
  var stream = through.obj(function(file, enc, callback) {
    if ('debug' === config.log) {
      app.use(function(req, res, next) {
        gutil.log(req.method + ' ' + req.url);

        next();
      });
    }

    app.use(serveStatic(file.path, {
      index: (config.directoryListing.enable ? false : config.defaultFile)
    }));

    if (config.livereload.enable) {
      watch(file.path, function(filename) {
        config.livereload.filter(filename, function(shouldReload) {
          if (shouldReload) {
            gutil.log('Livereload: file changed: ' + filename);
            config.livereload.io.sockets.emit('reload');
          }
        });
      });
    }

    this.push(file);

    callback();
  })
  .on('data', function() {
    // start the web server
    webserver.listen(config.port, config.host, openInBrowser);

    gutil.log('Webserver started at', gutil.colors.cyan('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port));
  });

  // once stream killed
  stream.on('kill', function() {
    webserver.close();

    if (config.livereload.enable) {
      config.livereload.ioServer.close();
    }
  });

  return stream;
};
<commit_msg>replaced semi-colon with comma<commit_after>"use strict";

var through = require('through2'),
  gutil = require('gulp-util'),
  http = require('http'),
  https = require('https'),
  inject = require('connect-inject'),
  connect = require('connect'),
  watch = require('node-watch'),
  fs = require('fs'),
  serveIndex = require('serve-index'),
  serveStatic = require('serve-static'),
  path = require('path'),
  open = require('open'),
  enableMiddlewareShorthand = require('./enableMiddlewareShorthand'),
  socket = require('socket.io');

module.exports = function(options) {
  var defaults = {
    /**
     *
     * BASIC DEFAULTS
     *
     **/
    host: 'localhost',
    port: 8000,
    defaultFile: 'index.html',
    https: false,
    open: false,
    log: 'info',
    clientConsole: false,

    /**
     *
     * MIDDLEWARE DEFAULTS
     *
     * NOTE:
     *  All middleware should defaults should have the 'enable'
     *  property if you want to support shorthand syntax like:
     *
     *    webserver({
     *      livereload: true
     *    });
     *
     */

    // Middleware: Livereload
    livereload: {
      enable: false,
      port: 35729,
      filter: function(filename, cb) {
        cb( !(/node_modules/.test(filename)) );
      }
    },

    // Middleware: Directory listing
    // For possible options, see:
    //  https://github.com/expressjs/serve-index
    directoryListing: {
      enable: false,
      path: './',
      options: undefined
    }
  };

  // Deep extend user provided options over the all of the defaults
  // Allow shorthand syntax, using the enable property as a flag
  var config = enableMiddlewareShorthand(defaults, options, ['directoryListing', 'livereload']);

  var openInBrowser = function () {
    if (config.open === false) return;
    open('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port);
    openInBrowser = undefined;
  };

  // connect app
  var app = connect();

  //  directory listing
  if (config.directoryListing.enable) {
    app.use(serveIndex(path.resolve(config.directoryListing.path), config.directoryListing.options));
  }

  // socket.io
  if (config.livereload.enable) {
    var ioServerOrigin = 'http://' + config.host + ':' + config.livereload.port;

    // socket.io won't load if requirejs is already loaded unless I disable it first
    var snippet = "<script type=\"text/javascript\">"
      + "var ___require, ___define;"
      + "if (typeof require !== 'undefined' && typeof requirejs !== 'undefined' && require === requirejs) {"
      + "    ___require = require;"
      + "    ___define = define;"
      + "    require = define = null;"
      + "}"
      + "</script>"
      + "<script type=\"text/javascript\" src=\"" + ioServerOrigin +"/socket.io.js\"></script>"
      + "<script type=\"text/javascript\">"
      + "if (___require) { require = ___require; define = ___define }"
      + "console.log('Connecting to livereload server..." + ioServerOrigin + "');"
      + "var ___socket = io.connect('" + ioServerOrigin +"');"
      + "___socket.on('connect', function() { console.log('Successfully connected to livereload server'); });"
      + "___socket.on('connect_error', function(err) { console.log('Failed to connect to livereload server: ' + err); });"
      + "___socket.on('reload', function() { location.reload(); });"
    ;

    if (config.clientConsole) {
      // sometimes socket.io fails to serialize arguments e.g. angular $state
      // socket.io can't handle cyclic objects either
      // some browsers don't have an .apply method on console methods
      snippet += "var ___console;"
        + "if (typeof console !== 'undefined') {"
        + " ___console = console;"
        + "};"
        + "var console = {};"
        + "(function(methods) {"
        + "    var methods = ['info','log','error','warn'];"
        + "    for (var i in methods) {"
        + "        console[methods[i]] = (function(method){"
        + "            return function() {"
        + "                var args = arguments, success;"
        + "                try { args = JSON.parse(JSON.stringify(args)); success = true; } catch(e) {"
        + "                    ___console.error(e + ', console.' + method + ' will not be sent to livereload server', args);"
        + "                }"
        + "                try { if (success) ___socket.emit('console_' + method, args); } catch(e) {}"
        + "                try { if (___console[method]) ___console[method].apply(null, arguments); } catch(e) {"
        + "                     ___console[method](arguments);"
        + "                }"
        + "            }"
        + "        }(methods[i]))"
        + "    }"
        + "}())"
      ;
    }

    snippet += "</script>";

    app.use(inject({
      snippet: snippet,
      rules: [{
        match: /<\/body>/,
        fn: function(w, s) {
          return s + w;
        }
      }]
    }));

    var io = config.livereload.io = socket();
    io.serveClient(true);
    io.path("");
    io.on('connection', function(socket){
      gutil.log('Livereload client connected');

      socket.on('console_log', function(data){
        var args = [
          gutil.colors.green('log')
        ];
        for (var i in data) {
          args.push(data[i]);
        }
        gutil.log.apply(null, args);
      });
      socket.on('console_warn', function(data){
        var args = [
          gutil.colors.yellow('warn')
        ];
        for (var i in data) {
          args.push(data[i]);
        }
        gutil.log.apply(null, args);
      });
      socket.on('console_info', function(data){
        var args = [
          gutil.colors.cyan('info')
        ];
        for (var i in data) {
          args.push(data[i]);
        }
        gutil.log.apply(null, args);
      });
      socket.on('console_error', function(data){
        var args = [
          gutil.colors.red('err')
        ];
        for (var i in data) {
          args.push(data[i]);
        }
        gutil.log.apply(null, args);
      });
    });
    io.attach(
      (config.livereload.ioServer = http.Server().listen(config.livereload.port))
    );
  }

  // http server
  var webserver = null;
  if (config.https) {
    var options = {
      key: fs.readFileSync(config.https.key || __dirname + '/../ssl/dev-key.pem'),
      cert: fs.readFileSync(config.https.cert || __dirname + '/../ssl/dev-cert.pem')
    };

    webserver = https.createServer(options, app);
  }
  else {
    webserver = http.createServer(app);
  }

  // Create server
  var stream = through.obj(function(file, enc, callback) {
    if ('debug' === config.log) {
      app.use(function(req, res, next) {
        gutil.log(req.method + ' ' + req.url);

        next();
      });
    }

    app.use(serveStatic(file.path, {
      index: (config.directoryListing.enable ? false : config.defaultFile)
    }));

    if (config.livereload.enable) {
      watch(file.path, function(filename) {
        config.livereload.filter(filename, function(shouldReload) {
          if (shouldReload) {
            gutil.log('Livereload: file changed: ' + filename);
            config.livereload.io.sockets.emit('reload');
          }
        });
      });
    }

    this.push(file);

    callback();
  })
  .on('data', function() {
    // start the web server
    webserver.listen(config.port, config.host, openInBrowser);

    gutil.log('Webserver started at', gutil.colors.cyan('http' + (config.https ? 's' : '') + '://' + config.host + ':' + config.port));
  });

  // once stream killed
  stream.on('kill', function() {
    webserver.close();

    if (config.livereload.enable) {
      config.livereload.ioServer.close();
    }
  });

  return stream;
};
<|endoftext|>


<commit_before>// Copyright 2016 wkh237@github. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
// @flow

import {
  NativeModules,
  DeviceEventEmitter,
  NativeAppEventEmitter,
  Platform,
  AsyncStorage,
} from 'react-native'
import type {
  RNFetchBlobNative,
  RNFetchBlobConfig,
  RNFetchBlobStream,
  RNFetchBlobResponseInfo
} from './types'
import StatefulPromise from './class/StatefulPromise.js'
import fs from './fs'
import getUUID from './utils/uuid'
import base64 from 'base-64'
import polyfill from './polyfill'
import android from './android'
const {
  RNFetchBlobSession,
  readStream,
  createFile,
  unlink,
  exists,
  mkdir,
  session,
  writeStream,
  readFile,
  ls,
  isDir,
  mv,
  cp
} = fs

const Blob = polyfill.Blob
const emitter = DeviceEventEmitter
const RNFetchBlob:RNFetchBlobNative = NativeModules.RNFetchBlob

// register message channel event handler.
emitter.addListener("RNFetchBlobMessage", (e) => {
  if(e.event === 'warn') {
    console.warn(e.detail)
  }
  else if (e.event === 'error') {
    throw e.detail
  }
  else {
    console.log("RNFetchBlob native message", e.detail)
  }
})

// Show warning if native module not detected
if(!RNFetchBlob || !RNFetchBlob.fetchBlobForm || !RNFetchBlob.fetchBlob) {
  console.warn(
    'react-native-fetch-blob could not find valid native module.',
    'please make sure you have linked native modules using `rnpm link`,',
    'and restart RN packager or manually compile IOS/Android project.'
  )
}

function wrap(path:string):string {
  return 'RNFetchBlob-file://' + path
}

/**
 * Calling this method will inject configurations into followed `fetch` method.
 * @param  {RNFetchBlobConfig} options
 *         Fetch API configurations, contains the following options :
 *         @property {boolean} fileCache
 *                   When fileCache is `true`, response data will be saved in
 *                   storage with a random generated file name, rather than
 *                   a BASE64 encoded string.
 *         @property {string} appendExt
 *                   Set this property to change file extension of random-
 *                   generated file name.
 *         @property {string} path
 *                   If this property has a valid string format, resonse data
 *                   will be saved to specific file path. Default string format
 *                   is : `RNFetchBlob-file://path-to-file`
 *         @property {string} key
 *                   If this property is set, it will be converted to md5, to
 *                   check if a file with this name exists.
 *                   If it exists, the absolute path is returned (no network
 *                   activity takes place )
 *                   If it doesn't exist, the file is downloaded as usual
 *         @property {number} timeout
 *                   Request timeout in millionseconds, by default it's 30000ms.
 *
 * @return {function} This method returns a `fetch` method instance.
 */
function config (options:RNFetchBlobConfig) {
  return { fetch : fetch.bind(options) }
}

/**
 * Create a HTTP request by settings, the `this` context is a `RNFetchBlobConfig` object.
 * @param  {string} method HTTP method, should be `GET`, `POST`, `PUT`, `DELETE`
 * @param  {string} url Request target url string.
 * @param  {object} headers HTTP request headers.
 * @param  {string} body
 *         Request body, can be either a BASE64 encoded data string,
 *         or a file path with prefix `RNFetchBlob-file://` (can be changed)
 * @return {Promise}
 *         This promise instance also contains a Customized method `progress`for
 *         register progress event handler.
 */
function fetch(...args:any):Promise {

  // create task ID for receiving progress event
  let taskId = getUUID()
  let options = this || {}
  let subscription, subscriptionUpload, stateEvent
  let respInfo = {}

  let promise = new Promise((resolve, reject) => {
    let [method, url, headers, body] = [...args]
    let nativeMethodName = Array.isArray(body) ? 'fetchBlobForm' : 'fetchBlob'

    // on progress event listener
    subscription = emitter.addListener('RNFetchBlobProgress', (e) => {
      if(e.taskId === taskId && promise.onProgress) {
        promise.onProgress(e.written, e.total)
      }
    })

    subscriptionUpload = emitter.addListener('RNFetchBlobProgress-upload', (e) => {
      if(e.taskId === taskId && promise.onUploadProgress) {
        promise.onUploadProgress(e.written, e.total)
      }
    })

    stateEvent = emitter.addListener('RNFetchBlobState', (e) => {
      respInfo = e
      if(e.taskId === taskId && promise.onStateChange) {
        promise.onStateChange(e)
      }
    })

    // When the request body comes from Blob polyfill, we should use special its ref
    // as the request body
    if( body instanceof Blob && body.isRNFetchBlobPolyfill) {
      body = body.getRNFetchBlobRef()
    }

    let req = RNFetchBlob[nativeMethodName]

    /**
     * Send request via native module, the response callback accepts three arguments
     * @callback
     * @param err {any} Error message or object, when the request success, this
     *                  parameter should be `null`.
     * @param rawType { 'utf8' | 'base64' | 'path'} RNFB request will be stored
     *                  as UTF8 string, BASE64 string, or a file path reference
     *                  in JS context, and this parameter indicates which one
     *                  dose the response data presents.
     * @param data {string} Response data or its reference.
     */
    req(options, taskId, method, url, headers || {}, body, (err, rawType, data) => {

      // task done, remove event listeners
      subscription.remove()
      subscriptionUpload.remove()
      stateEvent.remove()
      delete promise['progress']
      delete promise['uploadProgress']
      delete promise['stateChange']
      delete promise['cancel']

      if(err)
        reject(new Error(err, respInfo))
      else {
        // response data is saved to storage, create a session for it
        if(options.path || options.fileCache || options.addAndroidDownloads
          || options.key || options.auto && respInfo.respType === 'blob') {
          if(options.session)
            session(options.session).add(data)
        }
        respInfo.rnfbEncode = rawType
        resolve(new FetchBlobResponse(taskId, respInfo, data))
      }

    })

  })

  // extend Promise object, add `progress`, `uploadProgress`, and `cancel`
  // method for register progress event handler and cancel request.
  promise.progress = (fn) => {
    promise.onProgress = fn
    RNFetchBlob.enableProgressReport(taskId)
    return promise
  }
  promise.uploadProgress = (fn) => {
    promise.onUploadProgress = fn
    RNFetchBlob.enableUploadProgressReport(taskId)
    return promise
  }
  promise.stateChange = (fn) => {
    promise.onStateChange = fn
    return promise
  }
  promise.cancel = (fn) => {
    fn = fn || function(){}
    subscription.remove()
    subscriptionUpload.remove()
    stateEvent.remove()
    RNFetchBlob.cancelRequest(taskId, fn)
  }
  promise.taskId = taskId

  return promise

}

/**
 * RNFetchBlob response object class.
 */
class FetchBlobResponse {

  taskId : string;
  path : () => string | null;
  type : 'base64' | 'path' | 'utf8';
  data : any;
  blob : (contentType:string, sliceSize:number) => null;
  text : () => string;
  json : () => any;
  base64 : () => any;
  flush : () => void;
  respInfo : RNFetchBlobResponseInfo;
  session : (name:string) => RNFetchBlobSession | null;
  readFile : (encode: 'base64' | 'utf8' | 'ascii') => ?Promise;
  readStream : (
    encode: 'utf8' | 'ascii' | 'base64',
  ) => RNFetchBlobStream | null;

  constructor(taskId:string, info:RNFetchBlobResponseInfo, data:any) {
    this.data = data
    this.taskId = taskId
    this.type = info.rnfbEncode
    this.respInfo = info

    this.info = ():RNFetchBlobResponseInfo => {
      return this.respInfo
    }
    /**
     * Convert result to javascript RNFetchBlob object.
     * @return {Promise<Blob>} Return a promise resolves Blob object.
     */
    this.blob = ():Promise<Blob> => {
      let Blob = polyfill.Blob
      let cType = info.headers['Content-Type'] || info.headers['content-type']
      return new Promise((resolve, reject) => {
        switch(this.type) {
          case 'base64':
            Blob.build(this.data, { type : cType + ';BASE64' }).then(resolve)
          break
          case 'path':
            polyfill.Blob.build(wrap(this.data), { type : cType }).then(resolve)
          break
          default:
            polyfill.Blob.build(this.data, { type : 'text/plain' }).then(resolve)
          break
        }
      })
    }
    /**
     * Convert result to text.
     * @return {string} Decoded base64 string.
     */
    this.text = ():string => {
      let res = this.data
      switch(this.type) {
        case 'base64':
          return base64.decode(this.data)
        break
        case 'path':
          return fs.readFile(this.data, 'base64').then((b64) => Promise.resolve(base64.decode(b64)))
        break
        default:
          return this.data
        break
      }
    }
    /**
     * Convert result to JSON object.
     * @return {object} Parsed javascript object.
     */
    this.json = ():any => {
      switch(this.type) {
        case 'base64':
          return JSON.parse(base64.decode(this.data))
        break
        case 'path':
          return fs.readFile(this.data, 'utf8')
                   .then((text) => Promise.resolve(JSON.parse(text)))
        break
        default:
          return JSON.parse(this.data)
        break
      }
    }
    /**
     * Return BASE64 string directly.
     * @return {string} BASE64 string of response body.
     */
    this.base64 = ():string => {
      switch(this.type) {
        case 'base64':
          return this.data
        break
        case 'path':
          return fs.readFile(this.data, 'base64')
        break
        default:
          return base64.encode(this.data)
        break
      }
    }
    /**
     * Remove cahced file
     * @return {Promise}
     */
    this.flush = () => {
      let path = this.path()
      if(!path || this.type !== 'path')
        return
      return unlink(path)
    }
    /**
     * get path of response temp file
     * @return {string} File path of temp file.
     */
    this.path = () => {
      if(this.type === 'path')
        return this.data
      return null
    }

    this.session = (name:string):RNFetchBlobSession | null => {
      if(this.type === 'path')
        return session(name).add(this.data)
      else {
        console.warn('only file paths can be add into session.')
        return null
      }
    }
    /**
     * Start read stream from cached file
     * @param  {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
     * @param  {Function} fn On data event handler
     * @return {void}
     */
    this.readStream = (encode: 'base64' | 'utf8' | 'ascii'):RNFetchBlobStream | null => {
      if(this.type === 'path') {
        return readStream(this.data, encode)
      }
      else {
        console.warn('RNFetchblob', 'this response data does not contains any available stream')
        return null
      }
    }
    /**
     * Read file content with given encoding, if the response does not contains
     * a file path, show warning message
     * @param  {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
     * @return {String}
     */
    this.readFile = (encode: 'base64' | 'utf8' | 'ascii') => {
      if(this.type === 'path') {
        encode = encode || 'utf8'

        return readFile(this.data, encode)
      }
      else {
        console.warn('RNFetchblob', 'this response does not contains a readable file')
        return null
      }
    }
  }

}

export default {
  fetch,
  base64,
  android,
  config,
  session,
  fs,
  wrap,
  polyfill
}
<commit_msg>Fix unexpected warning message when canceling finished HTTP task<commit_after>// Copyright 2016 wkh237@github. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
// @flow

import {
  NativeModules,
  DeviceEventEmitter,
  NativeAppEventEmitter,
  Platform,
  AsyncStorage,
} from 'react-native'
import type {
  RNFetchBlobNative,
  RNFetchBlobConfig,
  RNFetchBlobStream,
  RNFetchBlobResponseInfo
} from './types'
import StatefulPromise from './class/StatefulPromise.js'
import fs from './fs'
import getUUID from './utils/uuid'
import base64 from 'base-64'
import polyfill from './polyfill'
import android from './android'
const {
  RNFetchBlobSession,
  readStream,
  createFile,
  unlink,
  exists,
  mkdir,
  session,
  writeStream,
  readFile,
  ls,
  isDir,
  mv,
  cp
} = fs

const Blob = polyfill.Blob
const emitter = DeviceEventEmitter
const RNFetchBlob:RNFetchBlobNative = NativeModules.RNFetchBlob

// register message channel event handler.
emitter.addListener("RNFetchBlobMessage", (e) => {
  if(e.event === 'warn') {
    console.warn(e.detail)
  }
  else if (e.event === 'error') {
    throw e.detail
  }
  else {
    console.log("RNFetchBlob native message", e.detail)
  }
})

// Show warning if native module not detected
if(!RNFetchBlob || !RNFetchBlob.fetchBlobForm || !RNFetchBlob.fetchBlob) {
  console.warn(
    'react-native-fetch-blob could not find valid native module.',
    'please make sure you have linked native modules using `rnpm link`,',
    'and restart RN packager or manually compile IOS/Android project.'
  )
}

function wrap(path:string):string {
  return 'RNFetchBlob-file://' + path
}

/**
 * Calling this method will inject configurations into followed `fetch` method.
 * @param  {RNFetchBlobConfig} options
 *         Fetch API configurations, contains the following options :
 *         @property {boolean} fileCache
 *                   When fileCache is `true`, response data will be saved in
 *                   storage with a random generated file name, rather than
 *                   a BASE64 encoded string.
 *         @property {string} appendExt
 *                   Set this property to change file extension of random-
 *                   generated file name.
 *         @property {string} path
 *                   If this property has a valid string format, resonse data
 *                   will be saved to specific file path. Default string format
 *                   is : `RNFetchBlob-file://path-to-file`
 *         @property {string} key
 *                   If this property is set, it will be converted to md5, to
 *                   check if a file with this name exists.
 *                   If it exists, the absolute path is returned (no network
 *                   activity takes place )
 *                   If it doesn't exist, the file is downloaded as usual
 *         @property {number} timeout
 *                   Request timeout in millionseconds, by default it's 30000ms.
 *
 * @return {function} This method returns a `fetch` method instance.
 */
function config (options:RNFetchBlobConfig) {
  return { fetch : fetch.bind(options) }
}

/**
 * Create a HTTP request by settings, the `this` context is a `RNFetchBlobConfig` object.
 * @param  {string} method HTTP method, should be `GET`, `POST`, `PUT`, `DELETE`
 * @param  {string} url Request target url string.
 * @param  {object} headers HTTP request headers.
 * @param  {string} body
 *         Request body, can be either a BASE64 encoded data string,
 *         or a file path with prefix `RNFetchBlob-file://` (can be changed)
 * @return {Promise}
 *         This promise instance also contains a Customized method `progress`for
 *         register progress event handler.
 */
function fetch(...args:any):Promise {

  // create task ID for receiving progress event
  let taskId = getUUID()
  let options = this || {}
  let subscription, subscriptionUpload, stateEvent
  let respInfo = {}

  let promise = new Promise((resolve, reject) => {
    let [method, url, headers, body] = [...args]
    let nativeMethodName = Array.isArray(body) ? 'fetchBlobForm' : 'fetchBlob'

    // on progress event listener
    subscription = emitter.addListener('RNFetchBlobProgress', (e) => {
      if(e.taskId === taskId && promise.onProgress) {
        promise.onProgress(e.written, e.total)
      }
    })

    subscriptionUpload = emitter.addListener('RNFetchBlobProgress-upload', (e) => {
      if(e.taskId === taskId && promise.onUploadProgress) {
        promise.onUploadProgress(e.written, e.total)
      }
    })

    stateEvent = emitter.addListener('RNFetchBlobState', (e) => {
      respInfo = e
      if(e.taskId === taskId && promise.onStateChange) {
        promise.onStateChange(e)
      }
    })

    // When the request body comes from Blob polyfill, we should use special its ref
    // as the request body
    if( body instanceof Blob && body.isRNFetchBlobPolyfill) {
      body = body.getRNFetchBlobRef()
    }

    let req = RNFetchBlob[nativeMethodName]

    /**
     * Send request via native module, the response callback accepts three arguments
     * @callback
     * @param err {any} Error message or object, when the request success, this
     *                  parameter should be `null`.
     * @param rawType { 'utf8' | 'base64' | 'path'} RNFB request will be stored
     *                  as UTF8 string, BASE64 string, or a file path reference
     *                  in JS context, and this parameter indicates which one
     *                  dose the response data presents.
     * @param data {string} Response data or its reference.
     */
    req(options, taskId, method, url, headers || {}, body, (err, rawType, data) => {

      // task done, remove event listeners
      subscription.remove()
      subscriptionUpload.remove()
      stateEvent.remove()
      delete promise['progress']
      delete promise['uploadProgress']
      delete promise['stateChange']
      delete promise['cancel']
      promise.cancel = () {
        console.warn('finished request could not be canceled')
      }

      if(err)
        reject(new Error(err, respInfo))
      else {
        // response data is saved to storage, create a session for it
        if(options.path || options.fileCache || options.addAndroidDownloads
          || options.key || options.auto && respInfo.respType === 'blob') {
          if(options.session)
            session(options.session).add(data)
        }
        respInfo.rnfbEncode = rawType
        resolve(new FetchBlobResponse(taskId, respInfo, data))
      }

    })

  })

  // extend Promise object, add `progress`, `uploadProgress`, and `cancel`
  // method for register progress event handler and cancel request.
  promise.progress = (fn) => {
    promise.onProgress = fn
    RNFetchBlob.enableProgressReport(taskId)
    return promise
  }
  promise.uploadProgress = (fn) => {
    promise.onUploadProgress = fn
    RNFetchBlob.enableUploadProgressReport(taskId)
    return promise
  }
  promise.stateChange = (fn) => {
    promise.onStateChange = fn
    return promise
  }
  promise.cancel = (fn) => {
    fn = fn || function(){}
    subscription.remove()
    subscriptionUpload.remove()
    stateEvent.remove()
    RNFetchBlob.cancelRequest(taskId, fn)
  }
  promise.taskId = taskId

  return promise

}

/**
 * RNFetchBlob response object class.
 */
class FetchBlobResponse {

  taskId : string;
  path : () => string | null;
  type : 'base64' | 'path' | 'utf8';
  data : any;
  blob : (contentType:string, sliceSize:number) => null;
  text : () => string;
  json : () => any;
  base64 : () => any;
  flush : () => void;
  respInfo : RNFetchBlobResponseInfo;
  session : (name:string) => RNFetchBlobSession | null;
  readFile : (encode: 'base64' | 'utf8' | 'ascii') => ?Promise;
  readStream : (
    encode: 'utf8' | 'ascii' | 'base64',
  ) => RNFetchBlobStream | null;

  constructor(taskId:string, info:RNFetchBlobResponseInfo, data:any) {
    this.data = data
    this.taskId = taskId
    this.type = info.rnfbEncode
    this.respInfo = info

    this.info = ():RNFetchBlobResponseInfo => {
      return this.respInfo
    }
    /**
     * Convert result to javascript RNFetchBlob object.
     * @return {Promise<Blob>} Return a promise resolves Blob object.
     */
    this.blob = ():Promise<Blob> => {
      let Blob = polyfill.Blob
      let cType = info.headers['Content-Type'] || info.headers['content-type']
      return new Promise((resolve, reject) => {
        switch(this.type) {
          case 'base64':
            Blob.build(this.data, { type : cType + ';BASE64' }).then(resolve)
          break
          case 'path':
            polyfill.Blob.build(wrap(this.data), { type : cType }).then(resolve)
          break
          default:
            polyfill.Blob.build(this.data, { type : 'text/plain' }).then(resolve)
          break
        }
      })
    }
    /**
     * Convert result to text.
     * @return {string} Decoded base64 string.
     */
    this.text = ():string => {
      let res = this.data
      switch(this.type) {
        case 'base64':
          return base64.decode(this.data)
        break
        case 'path':
          return fs.readFile(this.data, 'base64').then((b64) => Promise.resolve(base64.decode(b64)))
        break
        default:
          return this.data
        break
      }
    }
    /**
     * Convert result to JSON object.
     * @return {object} Parsed javascript object.
     */
    this.json = ():any => {
      switch(this.type) {
        case 'base64':
          return JSON.parse(base64.decode(this.data))
        break
        case 'path':
          return fs.readFile(this.data, 'utf8')
                   .then((text) => Promise.resolve(JSON.parse(text)))
        break
        default:
          return JSON.parse(this.data)
        break
      }
    }
    /**
     * Return BASE64 string directly.
     * @return {string} BASE64 string of response body.
     */
    this.base64 = ():string => {
      switch(this.type) {
        case 'base64':
          return this.data
        break
        case 'path':
          return fs.readFile(this.data, 'base64')
        break
        default:
          return base64.encode(this.data)
        break
      }
    }
    /**
     * Remove cahced file
     * @return {Promise}
     */
    this.flush = () => {
      let path = this.path()
      if(!path || this.type !== 'path')
        return
      return unlink(path)
    }
    /**
     * get path of response temp file
     * @return {string} File path of temp file.
     */
    this.path = () => {
      if(this.type === 'path')
        return this.data
      return null
    }

    this.session = (name:string):RNFetchBlobSession | null => {
      if(this.type === 'path')
        return session(name).add(this.data)
      else {
        console.warn('only file paths can be add into session.')
        return null
      }
    }
    /**
     * Start read stream from cached file
     * @param  {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
     * @param  {Function} fn On data event handler
     * @return {void}
     */
    this.readStream = (encode: 'base64' | 'utf8' | 'ascii'):RNFetchBlobStream | null => {
      if(this.type === 'path') {
        return readStream(this.data, encode)
      }
      else {
        console.warn('RNFetchblob', 'this response data does not contains any available stream')
        return null
      }
    }
    /**
     * Read file content with given encoding, if the response does not contains
     * a file path, show warning message
     * @param  {String} encoding Encode type, should be one of `base64`, `ascrii`, `utf8`.
     * @return {String}
     */
    this.readFile = (encode: 'base64' | 'utf8' | 'ascii') => {
      if(this.type === 'path') {
        encode = encode || 'utf8'

        return readFile(this.data, encode)
      }
      else {
        console.warn('RNFetchblob', 'this response does not contains a readable file')
        return null
      }
    }
  }

}

export default {
  fetch,
  base64,
  android,
  config,
  session,
  fs,
  wrap,
  polyfill
}
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, IndexRedirect, browserHistory} from 'react-router';
import App from './components/App';
import About from './components/About/About';
import Contact from './components/Contact/Contact';
import Thanks from './components/Contact/Thanks';

ReactDOM.render(
	<Router history={ browserHistory }>
		<Route path="/" component={ App }>
			<IndexRedirect to="/about" />
			<Route path="about" component={ About } />
			<Route path="contact" component={ Contact } />
			<Route path="contact/thanks" component={ Thanks } />
			<Route path="*" component={ About } />
		</Route>
	</Router>,
	document.getElementById('app')
);
<commit_msg>Redirect 404s to home for now<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, IndexRedirect, Redirect, browserHistory} from 'react-router';
import App from './components/App';
import About from './components/About/About';
import Contact from './components/Contact/Contact';
import Thanks from './components/Contact/Thanks';

ReactDOM.render(
	<Router history={ browserHistory }>
		<Route path="/" component={ App }>
			<IndexRedirect to="/about" />
			<Route path="about" component={ About } />
			<Route path="contact" component={ Contact } />
			<Route path="contact/thanks" component={ Thanks } />
			<Redirect from='*' to='/' />
		</Route>
	</Router>,
	document.getElementById('app')
);
<|endoftext|>


<commit_before>require('dotenv').config()

import {version} from '../package.json'
import path from 'path'

import Koa from 'koa'
import Route from 'koa-route'
import Serve from 'koa-static'

import Octokat from 'octokat'
import Badge from './Badge'

const app = new Koa()

app.context.github = new Octokat({
  token: process.env.GITHUB_TOKEN
})

const badge = new Badge(app.context, process.env)

app.use(Serve(path.join(__dirname, '../public'), {
  gzip: true,
  maxage: 31536000000
}))

app.use(Route.get('/', function * () {
  this.body = 'Hireable v' + version
}))

app.use(Route.get('/p/:user', function * (user) {
  this.redirect('https://github.com/' + user)
}))

app.use(Route.get('/:user/:repo?', function * show (id, repo) {
  yield badge.show(id, repo).then(src => {
    this.set('Cache-Control', 'no-cache, no-store, must-revalidate')
    this.redirect(src)
  })
}))

app.listen(process.env.APP_PORT)
console.log('Listening on :' + process.env.APP_PORT)
console.log('Visit http://localhost:' + process.env.APP_PORT)
<commit_msg>fix #1<commit_after>require('dotenv').config()

import {version} from '../package.json'
import path from 'path'
import crypto from 'crypto'

import Koa from 'koa'
import Route from 'koa-route'
import Serve from 'koa-static'

import Octokat from 'octokat'
import Badge from './Badge'

const app = new Koa()

app.context.github = new Octokat({
  token: process.env.GITHUB_TOKEN
})

const badge = new Badge(app.context, process.env)

app.use(Serve(path.join(__dirname, '../public'), {
  gzip: true,
  maxage: 0
}))

app.use(Route.get('/', function * () {
  this.body = 'Hireable v' + version
}))

app.use(Route.get('/p/:user', function * (user) {
  this.redirect('https://github.com/' + user)
}))

app.use(Route.get('/:user/:repo?', function * show (id, repo) {
  yield badge.show(id, repo).then(src => {
    this.body = null
    this.response.etag = crypto.createHash('md5').update(src).digest('hex')
    this.set('Cache-Control', 'no-cache, no-store, must-revalidate')
    this.redirect(src)
    this.status = 301
  })
}))

app.listen(process.env.APP_PORT)
console.log('Listening on :' + process.env.APP_PORT)
console.log('Visit http://localhost:' + process.env.APP_PORT)
<|endoftext|>


<commit_before>/**
 * Wrapper for arcgis api
 */
var rq = require('./lib/rq')
var uniq = require('./lib/uniq')

/**
 * Sets up a new arcgis client
 * @param {String} Valid Token
 * @returns {Object} Object with methods for necessary routes
 */
let client = token => {
  let ago = {
    /* Automatically add client id, base url */
    /**
     * Sets ups base request to ArcGIS
     * @param {String} URL to append to root URL
     * @param {Object} Options to pass as query parameters
     * @returns {Promise} On resolution will return results
     */
    request: (url, form = {}) => {
      form.token = token
      form.f     = 'pjson'
      return rq.get(`http://www.arcgis.com/sharing/rest/${url}`, form)
    },
    getItem: require('./get-item'),
    getOrganization: require('./get-organization'),
    getOrganizationUsers: require('./get-organization-users'),
    getOrganizationContent: require('./get-organization-content'),
    getGroup: require('./get-group'),
    getTags: require('./get-tags')
  }
  return ago
}<commit_msg>export client whoops<commit_after>/**
 * Wrapper for arcgis api
 */
var rq = require('./lib/rq')
var uniq = require('./lib/uniq')

/**
 * Sets up a new arcgis client
 * @param {String} Valid Token
 * @returns {Object} Object with methods for necessary routes
 */
let client = token => {
  let ago = {
    /* Automatically add client id, base url */
    /**
     * Sets ups base request to ArcGIS
     * @param {String} URL to append to root URL
     * @param {Object} Options to pass as query parameters
     * @returns {Promise} On resolution will return results
     */
    request: (url, form = {}) => {
      form.token = token
      form.f     = 'pjson'
      return rq.get(`http://www.arcgis.com/sharing/rest/${url}`, form)
    },
    getItem: require('./get-item'),
    getOrganization: require('./get-organization'),
    getOrganizationUsers: require('./get-organization-users'),
    getOrganizationContent: require('./get-organization-content'),
    getGroup: require('./get-group'),
    getTags: require('./get-tags')
  }
  return ago
}

module.exports = client<|endoftext|>


<commit_before>import {app} from 'hyperapp'
import {actions} from './actions/'
import {state} from './state/'
import {view} from './views/'
import {registerWorker} from './utils/register-worker'

app({
  actions,
  root,
  state,
  view
},
document.getElementById('root'))

// Register service worker if not on localhost
const local = window.location.host.startsWith('localhost')
if ('serviceWorker' in navigator && !local) {
  registerWorker()
}
<commit_msg>Update index.js<commit_after>import {app} from 'hyperapp'
import {actions} from './actions/'
import {state} from './state/'
import {view} from './views/'
import {registerWorker} from './utils/register-worker'

app({
  actions,
  root,
  state,
  view
},
document.getElementById('root'))

registerWorker()
<|endoftext|>


<commit_before>import { createFilter } from 'rollup-pluginutils';
import { writeFile } from 'fs';

import vueTransform from './vueTransform';

export default function vue(options = {}) {
    const filter = createFilter(options.include, options.exclude);
    const cssContent = {};
    const cssLang = {};

    return {
        name: 'vue',
        transform(source, id) {
            if (!filter(id) || !id.endsWith('.vue')) {
                return null;
            }

            const ref = vueTransform(source, id);

            // Map of every stylesheet content
            cssContent[id] = ref.css || '';

            // Map of every stylesheet lang
            cssLang[id] = ref.cssLang || 'css';

            // Component javascript with inlined html template
            return ref.js;
        },
        ongenerate(opts) {
            if (options.css === false) {
                return;
            }

            // Combine all stylesheets
            let css = '';
            Object.keys(cssContent).forEach((key) => {
                css += cssContent[key];
            });

            // Emit styles through callback or file
            if (typeof options.css === 'function') {
                options.css(css);

                return;
            }

            if (typeof options.css !== 'string') {
                // Don't create unwanted empty stylesheets
                if (!css.length) {
                    return;
                }

                // Guess destination filename
                let dest = opts.dest || 'bundle.js';
                if (dest.endsWith('.js')) {
                    dest = dest.slice(0, -3);
                }
                /* eslint-disable */
                options.css = `${dest}.css`;
                /* eslint-enable */
            }

            writeFile(options.css, css, (err) => {
                if (err) {
                    throw err;
                }
                emitted(options.css, css.length);
            });
        },
    };
}

function emitted(text, bytes) {
    console.log(green(text), getSize(bytes));
}

function green(text) {
    return `\u001b[1m\u001b[32m${text}\u001b[39m\u001b[22m`;
}

function getSize(size) {
    const bytes = size / 1024;
    return bytes < 1000 ? `${bytes.toPrecision(3)} kB` : `${(bytes / 1024).toPrecision(3)} MB`;
}
<commit_msg>Hack: replace process.env.NODE_ENV in vue.common.js<commit_after>import { createFilter } from 'rollup-pluginutils';
import { writeFile } from 'fs';

import vueTransform from './vueTransform';

export default function vue(options = {}) {
    const filter = createFilter(options.include, options.exclude);
    const cssContent = {};
    const cssLang = {};

    return {
        name: 'vue',
        transform(source, id) {
            if (!filter(id) || !id.endsWith('.vue')) {
                if (id.endsWith('vue.common.js')) {
                    return source.replace(/process\.env\.NODE_ENV/g, process.env.NODE_ENV || 'window.NODE_ENV')
                }
                return null;
            }

            const ref = vueTransform(source, id);

            // Map of every stylesheet content
            cssContent[id] = ref.css || '';

            // Map of every stylesheet lang
            cssLang[id] = ref.cssLang || 'css';

            // Component javascript with inlined html template
            return ref.js;
        },
        ongenerate(opts) {
            if (options.css === false) {
                return;
            }

            // Combine all stylesheets
            let css = '';
            Object.keys(cssContent).forEach((key) => {
                css += cssContent[key];
            });

            // Emit styles through callback or file
            if (typeof options.css === 'function') {
                options.css(css);

                return;
            }

            if (typeof options.css !== 'string') {
                // Don't create unwanted empty stylesheets
                if (!css.length) {
                    return;
                }

                // Guess destination filename
                let dest = opts.dest || 'bundle.js';
                if (dest.endsWith('.js')) {
                    dest = dest.slice(0, -3);
                }
                /* eslint-disable */
                options.css = `${dest}.css`;
                /* eslint-enable */
            }

            writeFile(options.css, css, (err) => {
                if (err) {
                    throw err;
                }
                emitted(options.css, css.length);
            });
        },
    };
}

function emitted(text, bytes) {
    console.log(green(text), getSize(bytes));
}

function green(text) {
    return `\u001b[1m\u001b[32m${text}\u001b[39m\u001b[22m`;
}

function getSize(size) {
    const bytes = size / 1024;
    return bytes < 1000 ? `${bytes.toPrecision(3)} kB` : `${(bytes / 1024).toPrecision(3)} MB`;
}
<|endoftext|>


<commit_before>
var MontageRequire = require("mr/require");
var File = require("../file");
var minifyJavaScript = require("../minify-javascript");
var jshint = require("../jshint").JSHINT;
var URL = require("url2");
var relativeToWorkingLocation = require("../util").relativeToWorkingLocation;

module.exports = transformJavaScript;
function transformJavaScript(file, config) {

    file.utf8 = file.utf8.replace(/^#!/, "//#!");

    if (config.lint && file.package.isMainPackage() && !jshint(file.utf8)) {
        config.out.warn("jshint " + relativeToWorkingLocation(file.location));
    }

    var id = file.relativeLocation.replace(/\.js$/, "");
    var dependencies = MontageRequire.parseDependencies(file.utf8);

    if (file.package.isMainPackage()) {
        if (id.toLowerCase() !== id) {
            config.out.warn("Module file name should be all lower-case " + relativeToWorkingLocation(file.location));
        }
        dependencies.forEach(function (dependency) {
            if (dependency.toLowerCase() !== dependency) {
                config.out.warn("Module identifier " + JSON.stringify(dependency) + " should be lower-case in " + relativeToWorkingLocation(file.location));
            }
        });
    }

    var definedContent = (
        "montageDefine(" +
            JSON.stringify(file.package.hash) + "," +
            JSON.stringify(id) + "," +
            "{" +
                "dependencies:" + JSON.stringify(dependencies) + "," +
                "factory:function(require,exports,module){" +
                    file.utf8 +
                "\n}" +
            "}" +
        ")"
    );
    var definedFile = new File({
        fs: config.fs,
        utf8: definedContent,
        path: file.path.replace(/\.js$/, ".load.js"),
        location: file.location.replace(/\.js$/, ".load.js"),
        relativeLocation: file.relativeLocation.replace(/\.js$/, ".load.js"),
        buildLocation: file.buildLocation.replace(/\.js$/, ".load.js"),
        package: file.package
    });
    config.files[definedFile.location] = definedFile;
    file.package.files[definedFile.relativeLocation] = definedFile;

    if (config.minify) {

        // minify original
        try {
            file.utf8 = minifyJavaScript(file.utf8, file.path);
        } catch (exception) {
            config.out.warn("JavaScript parse error in " + relativeToWorkingLocation(file.location) + ": " + exception.message);
        }

        // minify defined .load.js
        try {
            definedFile.utf8 = minifyJavaScript(definedFile.utf8, definedFile.path);
        } catch (exception) {
            config.out.warn("JavaScript parse error in " + definedFile.path + ": " + exception.message);
        }

    }
}

<commit_msg>Tolerate generated JavaScript files in transformer<commit_after>
var MontageRequire = require("mr/require");
var File = require("../file");
var minifyJavaScript = require("../minify-javascript");
var jshint = require("../jshint").JSHINT;
var URL = require("url2");
var relativeToWorkingLocation = require("../util").relativeToWorkingLocation;

module.exports = transformJavaScript;
function transformJavaScript(file, config) {

    file.utf8 = file.utf8.replace(/^#!/, "//#!");

    if (config.lint && file.package.isMainPackage() && !jshint(file.utf8)) {
        config.out.warn("jshint " + relativeToWorkingLocation(file.location));
    }

    var id = file.relativeLocation.replace(/\.js$/, "");
    var dependencies = MontageRequire.parseDependencies(file.utf8);

    if (file.package.isMainPackage()) {
        if (id.toLowerCase() !== id) {
            config.out.warn("Module file name should be all lower-case " + relativeToWorkingLocation(file.location));
        }
        dependencies.forEach(function (dependency) {
            if (dependency.toLowerCase() !== dependency) {
                config.out.warn("Module identifier " + JSON.stringify(dependency) + " should be lower-case in " + relativeToWorkingLocation(file.location));
            }
        });
    }

    var definedContent = (
        "montageDefine(" +
            JSON.stringify(file.package.hash) + "," +
            JSON.stringify(id) + "," +
            "{" +
                "dependencies:" + JSON.stringify(dependencies) + "," +
                "factory:function(require,exports,module){" +
                    file.utf8 +
                "\n}" +
            "}" +
        ")"
    );
    var definedFile = new File({
        fs: config.fs,
        utf8: definedContent,
        path: file.path ? file.path.replace(/\.js$/, ".load.js") : "",
        location: file.location.replace(/\.js$/, ".load.js"),
        relativeLocation: file.relativeLocation.replace(/\.js$/, ".load.js"),
        buildLocation: file.buildLocation.replace(/\.js$/, ".load.js"),
        package: file.package
    });
    config.files[definedFile.location] = definedFile;
    file.package.files[definedFile.relativeLocation] = definedFile;

    if (config.minify) {

        // minify original
        try {
            file.utf8 = minifyJavaScript(file.utf8, file.path);
        } catch (exception) {
            config.out.warn("JavaScript parse error in " + relativeToWorkingLocation(file.location) + ": " + exception.message);
        }

        // minify defined .load.js
        try {
            definedFile.utf8 = minifyJavaScript(definedFile.utf8, definedFile.path);
        } catch (exception) {
            config.out.warn("JavaScript parse error in " + definedFile.path + ": " + exception.message);
        }

    }
}

<|endoftext|>