<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  Image,
  TextInput,
  PanResponder,
  TouchableOpacity,
  View,
} = React;

var createReactIOSNativeComponentClass = require('createReactIOSNativeComponentClass');
var DeviceEventEmitter = require('RCTDeviceEventEmitter');
var Dimensions = require('Dimensions');

var CameraType = {
  CAMERA_FRONT: 0,
  CAMERA_BACK: 1,
};
var FlashType = {
  FLASH_AUTO: 0,
  FLASH_ON: 1,
  FLASH_OFF: 2,
};

var SCREEN_WIDTH = Dimensions.get('window').width;
var HEADER = '#3b5998';
var BGWASH = 'rgba(255,255,255,0.8)';
var DISABLED_WASH = 'rgba(255,255,255,0.25)';
var TEXT_BG = 'rgba(51, 102, 204,0.8)';

var CAMERA_REF = 'cameraview';

var MyCameraView = createReactIOSNativeComponentClass({
  validAttributes: { cameraType: 'camera-back' },
  uiViewClassName: 'MyCameraView',
});

var MyCameraViewMananger = require('NativeModules').MyCameraViewManager;

var SnapChatProject = React.createClass({

  _panResponder: {},
  _previousLeft: 0,
  _previousTop: 0,
  _textStyles: {},
  MAX_TOP:(SCREEN_WIDTH - 28)/2,
  textView: (null : ?React.Element),

  getInitialState: function() {
      return {
        cameraType: CameraType.CAMERA_FRONT,
        hasFlash: false,
        flashType: FlashType.FLASH_AUTO,
        takenPhotoURI: null,
        showTextInput: false,
      };
  },

  componentWillMount: function() {
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder,
      onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
      onPanResponderGrant: this._handlePanResponderGrant,
      onPanResponderMove: this._handlePanResponderMove,
      onPanResponderRelease: this._handlePanResponderEnd,
      onPanResponderTerminate: this._handlePanResponderEnd,
    });
  },

  componentDidMount: function() {
    MyCameraViewMananger.checkFlashLightSupport(
      this.state.cameraType,
      this._onHasFlashSuccess
    );
    DeviceEventEmitter.addListener(
      'takePhotoFinishData',
      this._onTakePhotoSuccess
    );
  },
  _onTakePhotoSuccess: function(data) {
    console.log('data data = ' + data.name);
    this.setState({
      'takenPhotoURI': data.name,
    });
  },
  _onHasFlashSuccess: function(hasFlash) {
    this.setState({
      'hasFlash': hasFlash,
    });
  },

  render: function() {
    if (this.state.takenPhotoURI){
      return this.renderEditPhotoUI();
    }

    return this.renderTakePhotoUI();
  },

  renderEditPhotoUI: function() {
    var photoImage = this.renderPhoto();

    var topBar = this.renderTopBar(this.resetUIToRetakePhoto, 'Re-take', this.addText, 'Add Text');
    var bottomBar = this.renderBottomBar(this.sharePhoto, require('image!send_btn'));

    return (
      <View style={styles.container}>
        {topBar}
        {photoImage}
        {bottomBar}
      </View>
    );
  },

  renderTakePhotoUI: function() {
    var flipCameraText = (this.state.cameraType == CameraType.CAMERA_FRONT) ? 'Front Camera' : 'Back Camera';
    var flashToggleText = this.getFlashButtonText(this.state.flashType);
    var topBar = this.renderTopBar(this.flipCamera, flipCameraText, null, null);
    if (this.state.hasFlash == true){
      topBar = this.renderTopBar(this.flipCamera, flipCameraText, this.flashToggle, flashToggleText);
    }

    var bottomBar = this.renderBottomBar(this.takePhoto, require('image!takephoto_btn'));
    var cameraView = <MyCameraView ref={CAMERA_REF} style={styles.cameraContainer}/>;

    return (
      <View style={styles.container}>
        {topBar}
        {cameraView}
        {bottomBar}
      </View>
    );
  },

  renderPhoto: function(){
    var inputText;
    var text;

    if (this.state.showTextInput) inputText = this.renderTextInput();
    else {
      if (this.state.inputText){
        text = (<Text ref={(text) => { this.textView = text; }}
                      style={styles.text}
                      {...this._panResponder.panHandlers}>{this.state.inputText}</Text>);

        this._previousLeft = 0;
        this._previousTop = 0;
        this._textStyles = {
          left: this._previousLeft,
          top: this._previousTop,
        };
      }
    }

    return(
      <Image source={{uri: this.state.takenPhotoURI, isStatic: true}}
             style={styles.thumbnail}>
        {inputText}
        {text}
      </Image>
    );
  },

  renderTextInput: function() {
    var content = '';
    if (this.state.inputText) content = this.state.inputText;

    return (<TextInput
                style={styles.input}
                value = {content}
                autoFocus = {true}
                onChangeText = {(text) => this.setState({'inputText': text}) }
                onEndEditing = {() => this.setState({'showTextInput': false}) } >
              </TextInput>);

    this.setState({
      'showTextInput': true,
    });
  },

  renderTopBar: function(action1, text1, action2, text2) {
    var button1, button2;

    if (action1 && text1) button1 = this.renderUtilButton(action1, text1);
    if (action2 && text2) button2 = this.renderUtilButton(action2, text2);

    // return camera type and flash type buttons
    return (
      <View style={[styles.topBarRow]}>
        {button1}
        {button2}
      </View>
    );
  },

  renderBottomBar: function(action, buttonImage) {
    var button = this.renderUtilImageButton(action, buttonImage);

    return (
      <View style={styles.bottomBarRow}>
        {button}
      </View>
    );
  },

  renderUtilButton: function(action, text){
    return (
      <TouchableOpacity onPress={action}>
        <View style={styles.navButton}>
          <Text>
             {text}
          </Text>
        </View>
      </TouchableOpacity>
    );
  },

  renderUtilImageButton: function(action, buttonImage){
    return (
      <TouchableOpacity onPress={action}>
        <Image
          style={styles.imageButton}
          source={buttonImage}
        />
      </TouchableOpacity>
      );
  },

  getCameraViewHandle: function(): any {
    return this.refs[CAMERA_REF].getNodeHandle();
  },

  flipCamera: function() {
    var newCameraType = CameraType.CAMERA_BACK;
    if (this.state.cameraType == CameraType.CAMERA_BACK) newCameraType = CameraType.CAMERA_FRONT;
    MyCameraViewMananger.toggleCamera(newCameraType, this.getCameraViewHandle());
    this.setState({
      'cameraType': newCameraType ,
    });
    MyCameraViewMananger.checkFlashLightSupport(
      this.state.cameraType,
      this._onHasFlashSuccess
    );
  },

  flashToggle: function() {
    var newFlashType = this.getNextFlashType(this.state.flashType);
    MyCameraViewMananger.toggleFlash(newFlashType, this.getCameraViewHandle());
    this.setState({
      'flashType': newFlashType,
    });
  },

  takePhoto: function() {
    MyCameraViewMananger.takePhoto(this.getCameraViewHandle());
  },

  resetUIToRetakePhoto: function() {
    // reset state values to null
    this.setState({
      'takenPhotoURI': null,
      'showTextInput': false,
      'inputText': null,
    });
  },

  addText: function(){
    this.setState({
      'showTextInput': true,
    });
  },

  sharePhoto: function(){
    MyCameraViewMananger.sharePhoto(this.state.inputText, this.getTextPositionY());
  },

  _updatePosition: function() {
    //console.log('MAX_TOP ' + this.MAX_TOP + 'top ' + this._textStyles.top);
    this.textView && this.textView.setNativeProps(this._textStyles);
  },

  _handleStartShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
    // Should we become active when the user presses down on the circle?
    return true;
  },

  _handleMoveShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
    // Should we become active when the user moves a touch over the circle?
    return true;
  },

  _handlePanResponderGrant: function(e: Object, gestureState: Object) {

  },
  _handlePanResponderMove: function(e: Object, gestureState: Object) {
    // limit the movement inside image boundsthis._textStyles.left = 0;
    var newTopPos = this._previousTop + gestureState.dy;
    if (Math.abs(newTopPos) <= this.MAX_TOP){
      this._textStyles.top = this._previousTop + gestureState.dy;
    } else {
      this._textStyles.top = this.MAX_TOP;
      if (newTopPos < 0) this._textStyles.top = -this.MAX_TOP;
    }

    this._updatePosition();
  },
  _handlePanResponderEnd: function(e: Object, gestureState: Object) {
    //this._previousLeft += gestureState.dx;
    this._previousTop += gestureState.dy;
  },

  getTextPositionY: function(){
    var posY;
    console.log('this._textStyles.top = ' + this._textStyles.top);
    if (this._textStyles.top < 0) posY = this.MAX_TOP - Math.abs(this._textStyles.top);
    else posY = this.MAX_TOP + this._textStyles.top;

    // original image 640 x 640. calculate ratio value and multiply
    var ratio = 640 / SCREEN_WIDTH;
    return posY * ratio;
  },

  getFlashButtonText: function(flashType){
    switch (flashType) {
      case FlashType.FLASH_AUTO:
          return 'Flash: AUTO';
          break;
      case FlashType.FLASH_ON:
          return 'Flash: ON';
          break;
      case FlashType.FLASH_OFF:
          return 'Flash: OFF';
          break;
    }
  },

  getNextFlashType: function(flashType){
    switch (flashType) {
      case FlashType.FLASH_AUTO:
          return FlashType.FLASH_ON;
          break;
      case FlashType.FLASH_ON:
          return FlashType.FLASH_OFF;
          break;
      case FlashType.FLASH_OFF:
          return FlashType.FLASH_AUTO;
          break;
    }
  },

});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    top: 20,
    backgroundColor: HEADER,
  },
  topBarRow: {
    flexDirection: 'row',
    padding: 8,
  },
  bottomBarRow: {
    flexDirection: 'row',
    padding: 8,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: BGWASH,
  },
  cameraContainer: {
    width: SCREEN_WIDTH,
    height: SCREEN_WIDTH,
  },
  navButton: {
    width: 100,
    padding: 3,
    marginRight: 3,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: BGWASH,
    borderColor: 'transparent',
    borderRadius: 3,
  },
  imageButton: {
    width: 50,
    height: 50,
  },
  thumbnail: {
    height: SCREEN_WIDTH,
    width: SCREEN_WIDTH,
    resizeMode: Image.resizeMode.contain,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
  },
  input: {
    height: 28,
    width: SCREEN_WIDTH,
    backgroundColor: TEXT_BG,
    fontSize: 20,
    textAlign: 'center',
    color: 'white',
  },
  text: {
    width: SCREEN_WIDTH,
    height: 28,
    fontSize: 20,
    textAlign: 'center',
    containerBackgroundColor: TEXT_BG,
    color: 'white',
  }
});

AppRegistry.registerComponent('SnapChatProject', () => SnapChatProject);
<commit_msg>Update style name for clearer meaning<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  Image,
  TextInput,
  PanResponder,
  TouchableOpacity,
  View,
} = React;

var createReactIOSNativeComponentClass = require('createReactIOSNativeComponentClass');
var DeviceEventEmitter = require('RCTDeviceEventEmitter');
var Dimensions = require('Dimensions');

var CameraType = {
  CAMERA_FRONT: 0,
  CAMERA_BACK: 1,
};
var FlashType = {
  FLASH_AUTO: 0,
  FLASH_ON: 1,
  FLASH_OFF: 2,
};

var SCREEN_WIDTH = Dimensions.get('window').width;
var HEADER = '#3b5998';
var BGWASH = 'rgba(255,255,255,0.8)';
var DISABLED_WASH = 'rgba(255,255,255,0.25)';
var TEXT_BG = 'rgba(51, 102, 204,0.8)';

var CAMERA_REF = 'cameraview';

var MyCameraView = createReactIOSNativeComponentClass({
  validAttributes: { cameraType: 'camera-back' },
  uiViewClassName: 'MyCameraView',
});

var MyCameraViewMananger = require('NativeModules').MyCameraViewManager;

var SnapChatProject = React.createClass({

  _panResponder: {},
  _previousLeft: 0,
  _previousTop: 0,
  _textStyles: {},
  MAX_TOP:(SCREEN_WIDTH - 28)/2,
  textView: (null : ?React.Element),

  getInitialState: function() {
      return {
        cameraType: CameraType.CAMERA_FRONT,
        hasFlash: false,
        flashType: FlashType.FLASH_AUTO,
        takenPhotoURI: null,
        showTextInput: false,
      };
  },

  componentWillMount: function() {
    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder,
      onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
      onPanResponderGrant: this._handlePanResponderGrant,
      onPanResponderMove: this._handlePanResponderMove,
      onPanResponderRelease: this._handlePanResponderEnd,
      onPanResponderTerminate: this._handlePanResponderEnd,
    });
  },

  componentDidMount: function() {
    MyCameraViewMananger.checkFlashLightSupport(
      this.state.cameraType,
      this._onHasFlashSuccess
    );
    DeviceEventEmitter.addListener(
      'takePhotoFinishData',
      this._onTakePhotoSuccess
    );
  },
  _onTakePhotoSuccess: function(data) {
    console.log('data data = ' + data.name);
    this.setState({
      'takenPhotoURI': data.name,
    });
  },
  _onHasFlashSuccess: function(hasFlash) {
    this.setState({
      'hasFlash': hasFlash,
    });
  },

  render: function() {
    if (this.state.takenPhotoURI){
      return this.renderEditPhotoUI();
    }

    return this.renderTakePhotoUI();
  },

  renderEditPhotoUI: function() {
    var photoImage = this.renderPhoto();

    var topBar = this.renderTopBar(this.resetUIToRetakePhoto, 'Re-take', this.addText, 'Add Text');
    var bottomBar = this.renderBottomBar(this.sharePhoto, require('image!send_btn'));

    return (
      <View style={styles.container}>
        {topBar}
        {photoImage}
        {bottomBar}
      </View>
    );
  },

  renderTakePhotoUI: function() {
    var flipCameraText = (this.state.cameraType == CameraType.CAMERA_FRONT) ? 'Front Camera' : 'Back Camera';
    var flashToggleText = this.getFlashButtonText(this.state.flashType);
    var topBar = this.renderTopBar(this.flipCamera, flipCameraText, null, null);
    if (this.state.hasFlash == true){
      topBar = this.renderTopBar(this.flipCamera, flipCameraText, this.flashToggle, flashToggleText);
    }

    var bottomBar = this.renderBottomBar(this.takePhoto, require('image!takephoto_btn'));
    var cameraView = <MyCameraView ref={CAMERA_REF} style={styles.cameraContainer}/>;

    return (
      <View style={styles.container}>
        {topBar}
        {cameraView}
        {bottomBar}
      </View>
    );
  },

  renderPhoto: function(){
    var inputText;
    var text;

    if (this.state.showTextInput) inputText = this.renderTextInput();
    else {
      if (this.state.inputText){
        text = (<Text ref={(text) => { this.textView = text; }}
                      style={styles.text}
                      {...this._panResponder.panHandlers}>{this.state.inputText}</Text>);

        this._previousLeft = 0;
        this._previousTop = 0;
        this._textStyles = {
          left: this._previousLeft,
          top: this._previousTop,
        };
      }
    }

    return(
      <Image source={{uri: this.state.takenPhotoURI, isStatic: true}}
             style={styles.thumbnail}>
        {inputText}
        {text}
      </Image>
    );
  },

  renderTextInput: function() {
    var content = '';
    if (this.state.inputText) content = this.state.inputText;

    return (<TextInput
                style={styles.inputText}
                value = {content}
                autoFocus = {true}
                onChangeText = {(text) => this.setState({'inputText': text}) }
                onEndEditing = {() => this.setState({'showTextInput': false}) } >
              </TextInput>);

    this.setState({
      'showTextInput': true,
    });
  },

  renderTopBar: function(action1, text1, action2, text2) {
    var button1, button2;

    if (action1 && text1) button1 = this.renderUtilButton(action1, text1);
    if (action2 && text2) button2 = this.renderUtilButton(action2, text2);

    // return camera type and flash type buttons
    return (
      <View style={[styles.topBarRow]}>
        {button1}
        {button2}
      </View>
    );
  },

  renderBottomBar: function(action, buttonImage) {
    var button = this.renderUtilImageButton(action, buttonImage);

    return (
      <View style={styles.bottomBarRow}>
        {button}
      </View>
    );
  },

  renderUtilButton: function(action, text){
    return (
      <TouchableOpacity onPress={action}>
        <View style={styles.navButton}>
          <Text>
             {text}
          </Text>
        </View>
      </TouchableOpacity>
    );
  },

  renderUtilImageButton: function(action, buttonImage){
    return (
      <TouchableOpacity onPress={action}>
        <Image
          style={styles.imageButton}
          source={buttonImage}
        />
      </TouchableOpacity>
      );
  },

  getCameraViewHandle: function(): any {
    return this.refs[CAMERA_REF].getNodeHandle();
  },

  flipCamera: function() {
    var newCameraType = CameraType.CAMERA_BACK;
    if (this.state.cameraType == CameraType.CAMERA_BACK) newCameraType = CameraType.CAMERA_FRONT;
    MyCameraViewMananger.toggleCamera(newCameraType, this.getCameraViewHandle());
    this.setState({
      'cameraType': newCameraType ,
    });
    MyCameraViewMananger.checkFlashLightSupport(
      this.state.cameraType,
      this._onHasFlashSuccess
    );
  },

  flashToggle: function() {
    var newFlashType = this.getNextFlashType(this.state.flashType);
    MyCameraViewMananger.toggleFlash(newFlashType, this.getCameraViewHandle());
    this.setState({
      'flashType': newFlashType,
    });
  },

  takePhoto: function() {
    MyCameraViewMananger.takePhoto(this.getCameraViewHandle());
  },

  resetUIToRetakePhoto: function() {
    // reset state values to null
    this.setState({
      'takenPhotoURI': null,
      'showTextInput': false,
      'inputText': null,
    });
  },

  addText: function(){
    this.setState({
      'showTextInput': true,
    });
  },

  sharePhoto: function(){
    MyCameraViewMananger.sharePhoto(this.state.inputText, this.getTextPositionY());
  },

  _updatePosition: function() {
    //console.log('MAX_TOP ' + this.MAX_TOP + 'top ' + this._textStyles.top);
    this.textView && this.textView.setNativeProps(this._textStyles);
  },

  _handleStartShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
    // Should we become active when the user presses down on the circle?
    return true;
  },

  _handleMoveShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
    // Should we become active when the user moves a touch over the circle?
    return true;
  },

  _handlePanResponderGrant: function(e: Object, gestureState: Object) {

  },
  _handlePanResponderMove: function(e: Object, gestureState: Object) {
    // limit the movement inside image boundsthis._textStyles.left = 0;
    var newTopPos = this._previousTop + gestureState.dy;
    if (Math.abs(newTopPos) <= this.MAX_TOP){
      this._textStyles.top = this._previousTop + gestureState.dy;
    } else {
      this._textStyles.top = this.MAX_TOP;
      if (newTopPos < 0) this._textStyles.top = -this.MAX_TOP;
    }

    this._updatePosition();
  },
  _handlePanResponderEnd: function(e: Object, gestureState: Object) {
    //this._previousLeft += gestureState.dx;
    this._previousTop += gestureState.dy;
  },

  getTextPositionY: function(){
    var posY;
    console.log('this._textStyles.top = ' + this._textStyles.top);
    if (this._textStyles.top < 0) posY = this.MAX_TOP - Math.abs(this._textStyles.top);
    else posY = this.MAX_TOP + this._textStyles.top;

    // original image 640 x 640. calculate ratio value and multiply
    var ratio = 640 / SCREEN_WIDTH;
    return posY * ratio;
  },

  getFlashButtonText: function(flashType){
    switch (flashType) {
      case FlashType.FLASH_AUTO:
          return 'Flash: AUTO';
          break;
      case FlashType.FLASH_ON:
          return 'Flash: ON';
          break;
      case FlashType.FLASH_OFF:
          return 'Flash: OFF';
          break;
    }
  },

  getNextFlashType: function(flashType){
    switch (flashType) {
      case FlashType.FLASH_AUTO:
          return FlashType.FLASH_ON;
          break;
      case FlashType.FLASH_ON:
          return FlashType.FLASH_OFF;
          break;
      case FlashType.FLASH_OFF:
          return FlashType.FLASH_AUTO;
          break;
    }
  },

});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    top: 20,
    backgroundColor: HEADER,
  },
  topBarRow: {
    flexDirection: 'row',
    padding: 8,
  },
  bottomBarRow: {
    flexDirection: 'row',
    padding: 8,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: BGWASH,
  },
  cameraContainer: {
    width: SCREEN_WIDTH,
    height: SCREEN_WIDTH,
  },
  navButton: {
    width: 100,
    padding: 3,
    marginRight: 3,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: BGWASH,
    borderColor: 'transparent',
    borderRadius: 3,
  },
  imageButton: {
    width: 50,
    height: 50,
  },
  thumbnail: {
    height: SCREEN_WIDTH,
    width: SCREEN_WIDTH,
    resizeMode: Image.resizeMode.contain,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
  },
  inputText: {
    height: 28,
    width: SCREEN_WIDTH,
    backgroundColor: TEXT_BG,
    fontSize: 20,
    textAlign: 'center',
    color: 'white',
  },
  text: {
    width: SCREEN_WIDTH,
    height: 28,
    fontSize: 20,
    textAlign: 'center',
    containerBackgroundColor: TEXT_BG,
    color: 'white',
  }
});

AppRegistry.registerComponent('SnapChatProject', () => SnapChatProject);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var haml = require('gulp-haml');
var postcss = require('gulp-postcss');
var postcss_cssnext = require('postcss-cssnext');
var precss = require('precss');
var clean_css = require('gulp-clean-css');
var concat_css = require('gulp-concat-css');
var uglify = require('gulp-uglify');
var pump = require('pump');

var paths = {
    haml: './src/haml/index.haml',
    haml_partials: './src/haml/partials/*.haml',
    postcss_src: './src/css/*.css',
    postcss_bin: './bin/css/',
    js_src: './src/js/*.js',
    js_bin: './bin/js/'
};

gulp.task('haml', function (callback) {
    pump([
        gulp.src(paths.haml),
        haml({ext: '.html'}),
        gulp.dest('./'),
        gulp.src(paths.haml_partials),
        haml({ext: '.html'}),
        gulp.dest('./bin/partials/'),
    ], callback);
});

gulp.task('css', function() {
    var processors = [
        postcss_cssnext,
        precss
    ];
    return gulp.src(paths.postcss_src)
    .pipe(postcss(processors))
    .pipe(concat_css('main.css'))
    .pipe(clean_css({
        debug: true
    }, function(details) {
        console.log(details.name + ': ' +
        (details.stats.originalSize / 1024).toFixed(2) + ' kB / ' +
        (details.stats.minifiedSize / 1024).toFixed(2) + ' kB');
    }))
    .pipe(gulp.dest(paths.postcss_bin));
});

gulp.task('js', function(callback){
    pump([
        gulp.src(paths.js_src),
        uglify(),
        gulp.dest(paths.js_bin),
        ], callback
    );
});

gulp.task('watch', function() {
    gulp.watch(paths.haml, ['haml']);
    gulp.watch(paths.haml_partials, ['haml']);
    gulp.watch(paths.postcss_src, ['css']);
    gulp.watch(paths.js_src, ['js']);
});

gulp.task('default', ['haml', 'css', 'js']);
<commit_msg>Gulpfile<commit_after>var gulp            = require('gulp');
var haml            = require('gulp-haml');
var postcss         = require('gulp-postcss');
var postcss_cssnext = require('postcss-cssnext');
var precss          = require('precss');
var clean_css       = require('gulp-clean-css');
var concat_css      = require('gulp-concat-css');
var uglify          = require('gulp-uglify');
var pump            = require('pump');

var paths = {
    haml:           './src/haml/index.haml',
    haml_partials:  './src/haml/partials/*.haml',
    postcss_src:    './src/css/*.css',
    postcss_bin:    './bin/css/',
    js_src:         './src/js/*.js',
    js_bin:         './bin/js/'
};

gulp.task('haml', function(callback) {
    pump([
        gulp.src(paths.haml),
        haml({ext: '.html'}),
        gulp.dest('./')
    ], callback);
});

gulp.task('haml-partials', function(callback) {
    pump([
        gulp.src(paths.haml_partials),
        haml({ext: '.html'}),
        gulp.dest('./bin/partials/')
    ], callback);
});

gulp.task('css', function() {
    var processors = [
        postcss_cssnext,
        precss
    ];
    return gulp.src(paths.postcss_src)
    .pipe(postcss(processors))
    .pipe(concat_css('main.css'))
    .pipe(clean_css())
    .pipe(gulp.dest(paths.postcss_bin));
});

gulp.task('js', function(callback){
    pump([
        gulp.src(paths.js_src),
        uglify(),
        gulp.dest(paths.js_bin),
    ], callback
);
});

gulp.task('watch', function() {
    gulp.watch(paths.haml, ['haml']);
    gulp.watch(paths.haml_partials, ['haml-partials']);
    gulp.watch(paths.postcss_src, ['css']);
    gulp.watch(paths.js_src, ['js']);
});

gulp.task('default', ['haml', 'haml-partials', 'css', 'js']);
<|endoftext|>


<commit_before>'use strict';
/**
 * gebo-performatives
 *
 * 2014 Daniel Bidulock
 * MIT
 */

module.exports = function() {
    var fs = require('fs'),
        https = require('https'),
        mime = require('mime');

    /**
     * Form data lines terminate with this for some reason
     */
    var CRLF = '\r\n';

    /**
     * Is a maximum length necessary?
     */
    var MAX_LENGTH = 70;

    /**
     * Alphanumerics
     */
    var POSSIBLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    /**
     * Get the boundary marker for multipart/form-data of the
     * specified length
     *
     * @param int
     *
     * @return string
     */
    function _getMultipartBoundary(length) {
        var boundary = '--';

        if (typeof length === undefined || length == null) {
          length = MAX_LENGTH;
        }
        else if (length < 0) {
          throw 'Boundary cannot have negative length';
        }
        else if (length > MAX_LENGTH) {
          throw 'Boundary length exceeded';
        }

        for (var i = 0; i < length; i++) {
          boundary += POSSIBLE.charAt(Math.floor(Math.random() * POSSIBLE.length));
        }

        return '---------------------------10102754414578508781458777923';
        //return boundary + CRLF;
      };
    exports.getMultipartBoundary = _getMultipartBoundary;

    /**
     * Take a standard gebo message and present it as
     * multipart/form-data.
     *
     * @param Object
     * @param callback
     */
    function _makeMultipartBody(message, done) {
        var error = false;

        var boundary = _getMultipartBoundary();
        var delimiter = CRLF + "--" + boundary;
        var closeDelimiter = delimiter + "--";

        var body = new Buffer(delimiter + CRLF);

        var keys = Object.keys(message);
        keys.forEach(function(key) {
            if (key.toLowerCase() === 'content') {
              body = Buffer.concat([body,
                                    new Buffer('Content-Disposition: form-data; name="content"' +
                                                CRLF + CRLF + JSON.stringify(message.content))]);
            }
            else if (key.toLowerCase() === 'files') {
              var files = Object.keys(message.files);
              files.forEach(function(file) {
                    try {
                      var data = fs.readFileSync(message.files[file].path);
                      body = Buffer.concat([body,
                                  new Buffer('Content-Disposition: form-data; name="' +
                                              file + '"; filename="' + message.files[file].name + '"' + CRLF),
                                  new Buffer('Content-Type: application/octet-stream' + CRLF + CRLF),
                                  data,
                            ]);
                    }
                    catch (err) {
                      error = true;
                      done(message.files[file].path + ' does not exist', null);
                    }
                });
            }
            else {
              body = Buffer.concat([body,
                                    new Buffer('Content-Disposition: form-data; name="'+
                                                key +'"' + CRLF + CRLF + message[key])]);
            }
            body = Buffer.concat([body, new Buffer(delimiter + CRLF)]);
          });

        // Add the closing boundary
        body = Buffer.concat([
                        body.slice(0, body.length - new Buffer(delimiter + CRLF).length),
                        new Buffer(closeDelimiter)
                    ]);

        if (!error) {
          done(null, body);
        }
      };
    exports.makeMultipartBody = _makeMultipartBody;

    /**
     * POST a request performative to the gebo provided
     * in the message
     *
     * @param Object
     * @param function
     */
    function _request(message, done) {
        _makeMultipartBody(message, function(err, str) {
            if (err) {
              done(err, null);
            }
            else {
              var multipartBody = new Buffer(str);
              var boundary = str.slice(0, str.indexOf(CRLF, 2)).trim();

              var options = {
                        hostname: message.gebo.replace(/^http[s]:\/\//i, ''),
                        port: 443,
                        path: '/perform',
                        method: 'POST',
                        rejectUnauthorized: false,
                        headers: { 'Content-Type': 'multipart/form-data; boundary=' + boundary.replace(/^--/, ''),
                                   'Content-Length': multipartBody.length },
                  };

              var req = https.request(options, function(res) {
                    var data = '';
                    res.setEncoding('utf8');

                    res.on('data', function(chunk) {
                        data += chunk;
                      });

                    res.on('end', function(err) {
                          if (err) {
                            done(err);
                          }
                          else {
                            done(null, data);
                          }
                      });
                });

              req.on('error', function(err) {
                    done(err);
                });

              req.write(multipartBody);
              req.end();
            }
          });
      };
    exports.request = _request;

    return exports;
}();
<commit_msg>Remove superfluous file<commit_after><|endoftext|>


<commit_before>import { generateUUID } from 'react-native-database';
import { batch } from 'react-redux';

import { UIDatabase, createRecord } from '../../database';
import {
  selectHasRefused,
  selectSelectedBatches,
  selectSelectedVaccinator,
} from '../../selectors/Entities/vaccinePrescription';
import { selectEditingNameId } from '../../selectors/Entities/name';
import { NameActions } from './NameActions';
import { NameNoteActions } from './NameNoteActions';
import { goBack, gotoVaccineDispensingPage } from '../../navigation/actions';

export const VACCINE_PRESCRIPTION_ACTIONS = {
  CREATE: 'VACCINE_PRESCRIPTION/create',
  SET_REFUSAL: 'VACCINE_PRESCRIPTION/setRefusal',
  RESET: 'VACCINE_PRESCRIPTION/reset',
  SELECT_VACCINE: 'VACCINE_PRESCRIPTION/selectVaccine',
  SELECT_BATCH: 'VACCINE_PRESCRIPTION/selectBatch',
  SELECT_VACCINATOR: 'VACCINE_PRESCRIPTION/selectVaccinator',
};

const createDefaultVaccinePrescription = () => ({
  id: generateUUID(),
  name: '',
  code: '',
  type: 'patient',
  isCustomer: false,
  isSupplier: false,
  isManufacturer: false,
  isVisible: true,
});

const getDefaultVaccinator = () => {
  const [batches] = UIDatabase.objects('TransactionBatch')
    .filtered('medicineAdministrator != null && itemBatch.item.isVaccine == true')
    .sorted('transaction.confirmDate', true);

  if (batches) {
    return batches.medicineAdministrator;
  }

  return null;
};

const getDefaultVaccine = () => {
  const [mostRecentTrans] = UIDatabase.objects('Transaction')
    .filtered("type == 'customer_invoice' && (status == 'finalised' || status == 'confirmed')")
    .sorted('confirmDate', true);

  const anyVaccine = UIDatabase.objects('Vaccine')[0];
  const mostRecentlyUsedVaccine = mostRecentTrans?.items?.filtered('item.isVaccine == true')[0]
    ?.item;

  const item = mostRecentlyUsedVaccine ?? anyVaccine;

  return item ?? null;
};

const getRecommendedBatch = vaccine => {
  const { batchesWithStock = [] } = vaccine ?? getDefaultVaccine() ?? {};

  if (batchesWithStock?.length) {
    const batchesByExpiry = batchesWithStock.sorted('expiryDate');
    const openVials = batchesByExpiry.filter(b => !Number.isInteger(b.numberOfPacks));

    return openVials.length ? openVials[0] : batchesByExpiry[0];
  }

  return null;
};

const create = () => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.CREATE,
  payload: {
    prescription: createDefaultVaccinePrescription(),
    vaccinator: getDefaultVaccinator(),
    selectedVaccines: [getDefaultVaccine()],
    selectedBatches: [getRecommendedBatch()],
  },
});

const reset = () => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.RESET,
});

const selectVaccine = vaccine => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_VACCINE,
  payload: { vaccine, batch: getRecommendedBatch(vaccine) },
});

const selectBatch = itemBatch => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_BATCH,
  payload: { itemBatch },
});

const setRefusal = hasRefused => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SET_REFUSAL,
  payload: {
    hasRefused,
    selectedVaccines: [getDefaultVaccine()],
    selectedBatches: [getRecommendedBatch()],
  },
});

const createPrescription = (patient, currentUser, selectedBatches, vaccinator) => {
  UIDatabase.write(() => {
    const prescription = createRecord(
      UIDatabase,
      'CustomerInvoice',
      patient,
      currentUser,
      'dispensary'
    );

    selectedBatches.forEach(itemBatch => {
      const { item } = itemBatch;
      const transactionItem = createRecord(UIDatabase, 'TransactionItem', prescription, item);
      createRecord(UIDatabase, 'TransactionBatch', transactionItem, itemBatch);
      transactionItem.setDoses(UIDatabase, 1);
      transactionItem.setVaccinator(UIDatabase, vaccinator);
    });
    prescription.finalise(UIDatabase);
  });
};

const createRefusalNameNote = name => {
  const [patientEvent] = UIDatabase.objects('PatientEvent').filtered('code == "RV"');

  if (!patientEvent) return;

  const id = generateUUID();
  const newNameNote = { id, name, patientEvent, entryDate: new Date() };

  UIDatabase.write(() => UIDatabase.create('NameNote', newNameNote));
};

const confirm = () => (dispatch, getState) => {
  const { user } = getState();
  const { currentUser } = user;
  const hasRefused = selectHasRefused(getState());
  const patientID = selectEditingNameId(getState());
  const selectedBatches = selectSelectedBatches(getState());
  const vaccinator = selectSelectedVaccinator(getState());

  batch(() => {
    dispatch(NameActions.saveEditing());
    dispatch(NameNoteActions.saveEditing());
    dispatch(reset());
  });

  const patient = UIDatabase.get('Name', patientID);
  if (hasRefused) {
    createRefusalNameNote(patient);
  } else {
    createPrescription(patient, currentUser, selectedBatches, vaccinator);
  }
};

const selectVaccinator = vaccinator => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_VACCINATOR,
  payload: { vaccinator },
});

const cancel = () => goBack();

const confirmAndRepeat = () => dispatch =>
  batch(() => {
    dispatch(confirm());
    dispatch(goBack());
    dispatch(gotoVaccineDispensingPage());
  });

export const VaccinePrescriptionActions = {
  cancel,
  confirm,
  create,
  reset,
  selectBatch,
  selectVaccine,
  setRefusal,
  selectVaccinator,
  confirmAndRepeat,
};
<commit_msg>Add corrected default vaccinator<commit_after>import { generateUUID } from 'react-native-database';
import { batch } from 'react-redux';

import { UIDatabase, createRecord } from '../../database';
import {
  selectHasRefused,
  selectSelectedBatches,
  selectSelectedVaccinator,
} from '../../selectors/Entities/vaccinePrescription';
import { selectEditingNameId } from '../../selectors/Entities/name';
import { NameActions } from './NameActions';
import { NameNoteActions } from './NameNoteActions';
import { goBack, gotoVaccineDispensingPage } from '../../navigation/actions';

export const VACCINE_PRESCRIPTION_ACTIONS = {
  CREATE: 'VACCINE_PRESCRIPTION/create',
  SET_REFUSAL: 'VACCINE_PRESCRIPTION/setRefusal',
  RESET: 'VACCINE_PRESCRIPTION/reset',
  SELECT_VACCINE: 'VACCINE_PRESCRIPTION/selectVaccine',
  SELECT_BATCH: 'VACCINE_PRESCRIPTION/selectBatch',
  SELECT_VACCINATOR: 'VACCINE_PRESCRIPTION/selectVaccinator',
};

const createDefaultVaccinePrescription = () => ({
  id: generateUUID(),
  name: '',
  code: '',
  type: 'patient',
  isCustomer: false,
  isSupplier: false,
  isManufacturer: false,
  isVisible: true,
});

const getDefaultVaccinator = () => {
  const [batches] = UIDatabase.objects('TransactionBatch')
    .filtered('medicineAdministrator != null && itemBatch.item.isVaccine == true')
    .sorted('transaction.confirmDate', true);

  if (batches) {
    return batches.medicineAdministrator;
  }

  return UIDatabase.objects('MedicineAdministrator').sorted('lastName')[0] ?? null;
};

const getDefaultVaccine = () => {
  const [mostRecentTrans] = UIDatabase.objects('Transaction')
    .filtered("type == 'customer_invoice' && (status == 'finalised' || status == 'confirmed')")
    .sorted('confirmDate', true);

  const anyVaccine = UIDatabase.objects('Vaccine')[0];
  const mostRecentlyUsedVaccine = mostRecentTrans?.items?.filtered('item.isVaccine == true')[0]
    ?.item;

  const item = mostRecentlyUsedVaccine ?? anyVaccine;

  return item ?? null;
};

const getRecommendedBatch = vaccine => {
  const { batchesWithStock = [] } = vaccine ?? getDefaultVaccine() ?? {};

  if (batchesWithStock?.length) {
    const batchesByExpiry = batchesWithStock.sorted('expiryDate');
    const openVials = batchesByExpiry.filter(b => !Number.isInteger(b.numberOfPacks));

    return openVials.length ? openVials[0] : batchesByExpiry[0];
  }

  return null;
};

const create = () => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.CREATE,
  payload: {
    prescription: createDefaultVaccinePrescription(),
    vaccinator: getDefaultVaccinator(),
    selectedVaccines: [getDefaultVaccine()],
    selectedBatches: [getRecommendedBatch()],
  },
});

const reset = () => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.RESET,
});

const selectVaccine = vaccine => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_VACCINE,
  payload: { vaccine, batch: getRecommendedBatch(vaccine) },
});

const selectBatch = itemBatch => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_BATCH,
  payload: { itemBatch },
});

const setRefusal = hasRefused => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SET_REFUSAL,
  payload: {
    hasRefused,
    selectedVaccines: [getDefaultVaccine()],
    selectedBatches: [getRecommendedBatch()],
  },
});

const createPrescription = (patient, currentUser, selectedBatches, vaccinator) => {
  UIDatabase.write(() => {
    const prescription = createRecord(
      UIDatabase,
      'CustomerInvoice',
      patient,
      currentUser,
      'dispensary'
    );

    selectedBatches.forEach(itemBatch => {
      const { item } = itemBatch;
      const transactionItem = createRecord(UIDatabase, 'TransactionItem', prescription, item);
      createRecord(UIDatabase, 'TransactionBatch', transactionItem, itemBatch);
      transactionItem.setDoses(UIDatabase, 1);
      transactionItem.setVaccinator(UIDatabase, vaccinator);
    });
    prescription.finalise(UIDatabase);
  });
};

const createRefusalNameNote = name => {
  const [patientEvent] = UIDatabase.objects('PatientEvent').filtered('code == "RV"');

  if (!patientEvent) return;

  const id = generateUUID();
  const newNameNote = { id, name, patientEvent, entryDate: new Date() };

  UIDatabase.write(() => UIDatabase.create('NameNote', newNameNote));
};

const confirm = () => (dispatch, getState) => {
  const { user } = getState();
  const { currentUser } = user;
  const hasRefused = selectHasRefused(getState());
  const patientID = selectEditingNameId(getState());
  const selectedBatches = selectSelectedBatches(getState());
  const vaccinator = selectSelectedVaccinator(getState());

  batch(() => {
    dispatch(NameActions.saveEditing());
    dispatch(NameNoteActions.saveEditing());
    dispatch(reset());
  });

  const patient = UIDatabase.get('Name', patientID);
  if (hasRefused) {
    createRefusalNameNote(patient);
  } else {
    createPrescription(patient, currentUser, selectedBatches, vaccinator);
  }
};

const selectVaccinator = vaccinator => ({
  type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_VACCINATOR,
  payload: { vaccinator },
});

const cancel = () => goBack();

const confirmAndRepeat = () => dispatch =>
  batch(() => {
    dispatch(confirm());
    dispatch(goBack());
    dispatch(gotoVaccineDispensingPage());
  });

export const VaccinePrescriptionActions = {
  cancel,
  confirm,
  create,
  reset,
  selectBatch,
  selectVaccine,
  setRefusal,
  selectVaccinator,
  confirmAndRepeat,
};
<|endoftext|>


<commit_before>import Path from 'path'
import fs from 'fs'
var Fs= core.System.IO.Fs
import Cp from 'child_process'
class Sites{

	constructor(){
		var dir= Path.join(process.env.HOME, "MachineConfig")
		// Lo primero es intentar montar el sitio donde va MachineConfig
		this.configureVirtioMount({
			src: "MachineConfig",
			dest: dir
		})

		var file= Path.join(dir, "machine.config.json")
		this.$= require(file)

	}

	get config(){
		return this.$
	}

	static startSite(domain, program, args){
		var pid
		var spawn = require('child_process').spawn

		var home= process.env.HOME + "/Magno_Sites/"
		if(!fs.existsSync(home))
			fs.mkdirSync(home)

		var pidFile= Path.join(home, domain)
		var logfile= Path.join(home, domain + ".log")
		var out = fs.openSync(logfile, 'a');
		var err = fs.openSync(logfile, 'a');

		if(fs.existsSync(pidFile)){
			pid=fs.readFileSync(pidFile)
			if(pid!=""){
				pid=pid|0
				if(pid>0){
					try{
						process.kill(pid,'SIGHUP')
					}
					catch(e){
						//
					}
				}
			}
		}

		const child = spawn(program, args, {
		 detached: true,
		 stdio: [ 'ignore', out, err ]
		})
		fs.writeFileSync(pidFile, child.pid.toString())
		child.unref()
	}

	static rmDir(dir){
		var file, files= fs.readdirSync(dir)
		for(var i=0;i<files.length;i++){
			file= files[i]
			if(file!="." && file!=".."){
				fs.unlinkSync(Path.join(dir, file))
			}
		}
	}

	configure(){
		Sites.rmDir("/etc/nginx/sites-enabled")
		Sites.rmDir("/etc/nginx/sites-available")

		var mountPoints= this.config.virtio

		for(var i=0;i<mountPoints.length;i++){
			this.configureVirtioMount(mountPoints[i])
		}

		var sites= this.config.sites
		for(var i=0;i<sites.length;i++){
			if(sites[i].type=="PHP")
				this.configurePhpSite(sites[i])

			else if(sites[i].type=="Proxy")
				this.configureProxySite(sites[i])
		}

		// Restart service ...
		Cp.execSync("service nginx restart")

	}

	configureVirtioMount(mount){
		if(!Fs.sync.exists(mount.dest)){
			Fs.sync.mkdir(mount.dest)
			try{
				Fs.sync.chmod(mount.dest, '666')
			}
			catch(e){}
		}

		Cp.execSync(`mount -t 9p -o trans=virtio,version=9p2000.L ${mount.src} "${mount.dest}"`)
	}

	configureProxySite(site){

		var domain= site.url
		var port= site.port
		var content=`
server {
    listen 80;

    server_name ${domain};

    location / {
        proxy_pass http://localhost:${port};
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}`

		var file= "/etc/nginx/sites-enabled/"+domain
		var file2= "/etc/nginx/sites-available/"+domain
		//var f= "/home/" + this.machine.config.user + "/" + domain

		Fs.sync.writeFile(file, content)
		Fs.sync.chmod(file, '664')

		Fs.sync.writeFile(file2, content)
		Fs.sync.chmod(file2, '664')

		// Verificar si el sitio necesita que se ejecute algún comando ...
		if(site.execute){
			f= Path.join(process.env.HOME, "start-site")
			Sites.startSite(site.url, site.execute.path, site.execute.arguments||[])

		}

	}

	configurePhpSite(site){
		var domain= site.url
		var root= site.to

		var content=
`server {
    listen 80;
    server_name ${domain};
    root "${root}";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/${domain}-error.log error;

    sendfile off;

    client_max_body_size 100m;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
    }

    location ~ /\.ht {
        deny all;
    }
}`

		var file= "/etc/nginx/sites-enabled/"+domain
		var file2= "/etc/nginx/sites-available/"+domain
		//var f= "/home/" + this.machine.config.user + "/" + domain

		Fs.sync.writeFile(file, content)
		Fs.sync.chmod(file, '664')

		Fs.sync.writeFile(file2, content)
		Fs.sync.chmod(file2, '664')

	}

}
export default Sites<commit_msg>Tratar de desmontar primero el sitio<commit_after>import Path from 'path'
import fs from 'fs'
var Fs= core.System.IO.Fs
import Cp from 'child_process'
class Sites{

	constructor(){
		var dir= Path.join(process.env.HOME, "MachineConfig")
		// Lo primero es intentar montar el sitio donde va MachineConfig
		this.configureVirtioMount({
			src: "MachineConfig",
			dest: dir
		})

		var file= Path.join(dir, "machine.config.json")
		this.$= require(file)

	}

	get config(){
		return this.$
	}

	static startSite(domain, program, args){
		var pid
		var spawn = require('child_process').spawn

		var home= process.env.HOME + "/Magno_Sites/"
		if(!fs.existsSync(home))
			fs.mkdirSync(home)

		var pidFile= Path.join(home, domain)
		var logfile= Path.join(home, domain + ".log")
		var out = fs.openSync(logfile, 'a');
		var err = fs.openSync(logfile, 'a');

		if(fs.existsSync(pidFile)){
			pid=fs.readFileSync(pidFile)
			if(pid!=""){
				pid=pid|0
				if(pid>0){
					try{
						process.kill(pid,'SIGHUP')
					}
					catch(e){
						//
					}
				}
			}
		}

		const child = spawn(program, args, {
		 detached: true,
		 stdio: [ 'ignore', out, err ]
		})
		fs.writeFileSync(pidFile, child.pid.toString())
		child.unref()
	}

	static rmDir(dir){
		var file, files= fs.readdirSync(dir)
		for(var i=0;i<files.length;i++){
			file= files[i]
			if(file!="." && file!=".."){
				fs.unlinkSync(Path.join(dir, file))
			}
		}
	}

	configure(){
		Sites.rmDir("/etc/nginx/sites-enabled")
		Sites.rmDir("/etc/nginx/sites-available")

		var mountPoints= this.config.virtio

		for(var i=0;i<mountPoints.length;i++){
			this.configureVirtioMount(mountPoints[i])
		}

		var sites= this.config.sites
		for(var i=0;i<sites.length;i++){
			if(sites[i].type=="PHP")
				this.configurePhpSite(sites[i])

			else if(sites[i].type=="Proxy")
				this.configureProxySite(sites[i])
		}

		// Restart service ...
		Cp.execSync("service nginx restart")

	}

	configureVirtioMount(mount){
		if(!Fs.sync.exists(mount.dest)){
			Fs.sync.mkdir(mount.dest)
			try{
				Fs.sync.chmod(mount.dest, '666')
			}
			catch(e){}
		}

		try{
			// Tratar de desmontar primero
			Cp.execSync(`umount "${mount.dest}"`)
		}
		catch(e){

		}

		Cp.execSync(`mount -t 9p -o trans=virtio,version=9p2000.L ${mount.src} "${mount.dest}"`)
	}

	configureProxySite(site){

		var domain= site.url
		var port= site.port
		var content=`
server {
    listen 80;

    server_name ${domain};

    location / {
        proxy_pass http://localhost:${port};
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}`

		var file= "/etc/nginx/sites-enabled/"+domain
		var file2= "/etc/nginx/sites-available/"+domain
		//var f= "/home/" + this.machine.config.user + "/" + domain

		Fs.sync.writeFile(file, content)
		Fs.sync.chmod(file, '664')

		Fs.sync.writeFile(file2, content)
		Fs.sync.chmod(file2, '664')

		// Verificar si el sitio necesita que se ejecute algún comando ...
		if(site.execute){
			f= Path.join(process.env.HOME, "start-site")
			Sites.startSite(site.url, site.execute.path, site.execute.arguments||[])

		}

	}

	configurePhpSite(site){
		var domain= site.url
		var root= site.to

		var content=
`server {
    listen 80;
    server_name ${domain};
    root "${root}";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/${domain}-error.log error;

    sendfile off;

    client_max_body_size 100m;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
    }

    location ~ /\.ht {
        deny all;
    }
}`

		var file= "/etc/nginx/sites-enabled/"+domain
		var file2= "/etc/nginx/sites-available/"+domain
		//var f= "/home/" + this.machine.config.user + "/" + domain

		Fs.sync.writeFile(file, content)
		Fs.sync.chmod(file, '664')

		Fs.sync.writeFile(file2, content)
		Fs.sync.chmod(file2, '664')

	}

}
export default Sites<|endoftext|>


<commit_before>"use strict";

require('babel-register');

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var assign = require('lodash.assign');
var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var del = require('del');
var glob = require('glob');
var istanbul = require('browserify-istanbul');
var source = require('vinyl-source-stream');
var tsify = require('tsify');
var watchify = require('watchify');

var Server = require('karma').Server;

var config = typeof $.util.env['configFile'] === 'string' ? require($.util.env['configFile']) : {};

gulp.task('clean', function () {
    del(['dist', 'test/build', 'opendolphin/build', 'opendolphin/test/build', 'coverage']);
});

/* START: lint */
//local report
gulp.task('lint:js', function () {
    return gulp.src(['./src/**/*.js', './test/src/**/*.js'])
        .pipe($.jshint())
        .pipe($.jshint.reporter('default'))
        .pipe($.jshint.reporter('fail'));
});

//local report
gulp.task('lint:es', function () {
    return gulp.src(['./src/**/*.es6', './test/src/**/*.es6'])
        .pipe($.eslint())
        .pipe($.eslint.format())
        .pipe($.eslint.failAfterError());
});

gulp.task('lint', ['lint:js', 'lint:es']);

/* END: lint */

/* START : build dolphin-platform related tests */

function rebundleTest(bundler) {
    return bundler
        .transform('babelify')
        .transform(istanbul({
            ignore: ['**/src/polyfills.js', '**/opendolphin/**/*.js']
        }))
        .bundle()
        .on('error', $.util.log.bind($.util, 'Browserify Error'))
        .pipe(source('test-bundle.js'))
        .pipe(buffer())
        .pipe($.sourcemaps.init({loadMaps: true}))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('./test/build'))
}

var testBundler = browserify(assign({}, watchify.args, {
    entries: glob.sync('./test/src/**/test-*.js'),
    debug: true
}));

gulp.task('build-test', ['build:od'], function () {
    return rebundleTest(testBundler);
});

gulp.task('test', ['build-test'], function (done) {
    new Server({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done).start();
});
/* END : build dolphin-platform related tests */

gulp.task('verify', ['lint', 'test']);

/* START: Building opendolphin and dolphin-platform.js */

//build opendolphin
gulp.task('build:od', function () {
    return gulp.src('opendolphin/js/dolphin/*.ts')
        .pipe($.typescript({
            module: 'commonjs'
        }))
        .pipe($.sourcemaps.init({loadMaps: true}))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('opendolphin/build/'));
});

var mainBundler = browserify(assign({}, watchify.args, {
    entries: './src/dolphin.js',
    standalone: 'dolphin',
    debug: true
}));

function rebundle(bundler) {
    return bundler
        .transform('babelify')
        .bundle()
        .on('error', $.util.log.bind($.util, 'Browserify Error'))
        .pipe(source('dolphin-platform.js'))
        .pipe($.derequire())
        .pipe(gulp.dest('./dist'))
        .pipe(buffer())
        .pipe($.rename({extname: '.min.js'}))
        .pipe($.sourcemaps.init({loadMaps: true}))
        .pipe($.uglify())
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('./dist'));
}
//build dolphin-platform
gulp.task('build', ['build:od'], function () {
    return rebundle(mainBundler);
});
/* END: Building opendolphin and dolphin-platform.js */

//Watching for changes
gulp.task('watch', function () {
    gulp.watch(['src/**', 'test/**'], ['test']);

    var watchedMainBundler = watchify(mainBundler);
    watchedMainBundler.on('update', function () {
        rebundle(watchedMainBundler)
    });

    var watchedTestBundler = watchify(testBundler);
    watchedTestBundler.on('update', function () {
        rebundleTest(watchedTestBundler)
    });
});

gulp.task('default', ['verify', 'build', 'watch']);

/* START: build opendolphin tests  */

gulp.task('build-test:od', ['build:od'], function () {
    var bundle = browserify({debug: true})
        .add(glob.sync('./opendolphin/test*/**/*.ts'))
        .add('./opendolphin/testrunner/tsUnitKarmaAdapter.js')
        .plugin(tsify);

    return bundle.bundle()
        .on('error', $.util.log.bind($.util, 'Browserify Error'))
        .pipe(source('test-bundle.js'))
        .pipe(buffer())
        .pipe($.sourcemaps.init({loadMaps: true}))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('./opendolphin/test/build'));
});

/* END: build opendolphin tests  */

gulp.task('ci-common', ['build', 'build-test', 'build-test:od']);

//Test opendolphin
gulp.task('ci-test:od', ['ci-common'], function(done) {
    new Server({
        configFile: __dirname + '/opendolphin/testrunner/karma.conf.js',
        reporters: ['coverage'],
        singleRun: true
    }, done).start();
});

//Test dolphin-platform
gulp.task('ci-test', ['ci-common'], function (done) {
    new Server({
        configFile: __dirname + '/karma.conf.js',
        reporters: ['teamcity', 'coverage'],
        coverageReporter: {
            reporters: [
                {type: 'lcovonly', subdir: '.'}
            ]
        },
        singleRun: true
    }, done).start();
});

gulp.task('ci', ['ci-common', 'ci-test' , 'ci-test:od' ]);

// START: Saucelabs

function createSauceLabsTestStep(customLaunchers, browsers, done) {
    return function () {
        new Server({
            configFile: __dirname + '/karma.conf.js',
            customLaunchers: customLaunchers,
            browsers: browsers,
            reporters: ['saucelabs'],
            singleRun: true
        },function(result){
            if(result === 0){
                done();
            } else {
                return done(new Error(`Karma exited with status code ${result}`));
            }
        }).start();
    }
}

function createSauceLabsTestPipe(customLaunchers, step) {
    // We cannot run too many instances at Sauce Labs in parallel, thus we need to run it several times
    // with only a few environments set
    var numSauceLabsVMs = 3;
    var allBrowsers = Object.keys(customLaunchers);

    while (allBrowsers.length > 0) {
        var browsers = [];
        for (var i = 0; i < numSauceLabsVMs && allBrowsers.length > 0; i++) {
            browsers.push(allBrowsers.shift());
        }

        step = createSauceLabsTestStep(customLaunchers, browsers, step);
    }

    step();
}

gulp.task('saucelabs', ['ci-common'], function (done) {
    var customLaunchers = require('./sauce.launchers.js').browsers;
    return createSauceLabsTestPipe(customLaunchers, done);
});
<commit_msg>Fail Travis build if saucelabs tests fail<commit_after>"use strict";

require('babel-register');

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var assign = require('lodash.assign');
var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var del = require('del');
var glob = require('glob');
var istanbul = require('browserify-istanbul');
var source = require('vinyl-source-stream');
var tsify = require('tsify');
var watchify = require('watchify');

var Server = require('karma').Server;

var config = typeof $.util.env['configFile'] === 'string' ? require($.util.env['configFile']) : {};

gulp.task('clean', function () {
    del(['dist', 'test/build', 'opendolphin/build', 'opendolphin/test/build', 'coverage']);
});

/* START: lint */
//local report
gulp.task('lint:js', function () {
    return gulp.src(['./src/**/*.js', './test/src/**/*.js'])
        .pipe($.jshint())
        .pipe($.jshint.reporter('default'))
        .pipe($.jshint.reporter('fail'));
});

//local report
gulp.task('lint:es', function () {
    return gulp.src(['./src/**/*.es6', './test/src/**/*.es6'])
        .pipe($.eslint())
        .pipe($.eslint.format())
        .pipe($.eslint.failAfterError());
});

gulp.task('lint', ['lint:js', 'lint:es']);

/* END: lint */

/* START : build dolphin-platform related tests */

function rebundleTest(bundler) {
    return bundler
        .transform('babelify')
        .transform(istanbul({
            ignore: ['**/src/polyfills.js', '**/opendolphin/**/*.js']
        }))
        .bundle()
        .on('error', $.util.log.bind($.util, 'Browserify Error'))
        .pipe(source('test-bundle.js'))
        .pipe(buffer())
        .pipe($.sourcemaps.init({loadMaps: true}))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('./test/build'))
}

var testBundler = browserify(assign({}, watchify.args, {
    entries: glob.sync('./test/src/**/test-*.js'),
    debug: true
}));

gulp.task('build-test', ['build:od'], function () {
    return rebundleTest(testBundler);
});

gulp.task('test', ['build-test'], function (done) {
    new Server({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done).start();
});
/* END : build dolphin-platform related tests */

gulp.task('verify', ['lint', 'test']);

/* START: Building opendolphin and dolphin-platform.js */

//build opendolphin
gulp.task('build:od', function () {
    return gulp.src('opendolphin/js/dolphin/*.ts')
        .pipe($.typescript({
            module: 'commonjs'
        }))
        .pipe($.sourcemaps.init({loadMaps: true}))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('opendolphin/build/'));
});

var mainBundler = browserify(assign({}, watchify.args, {
    entries: './src/dolphin.js',
    standalone: 'dolphin',
    debug: true
}));

function rebundle(bundler) {
    return bundler
        .transform('babelify')
        .bundle()
        .on('error', $.util.log.bind($.util, 'Browserify Error'))
        .pipe(source('dolphin-platform.js'))
        .pipe($.derequire())
        .pipe(gulp.dest('./dist'))
        .pipe(buffer())
        .pipe($.rename({extname: '.min.js'}))
        .pipe($.sourcemaps.init({loadMaps: true}))
        .pipe($.uglify())
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('./dist'));
}
//build dolphin-platform
gulp.task('build', ['build:od'], function () {
    return rebundle(mainBundler);
});
/* END: Building opendolphin and dolphin-platform.js */

//Watching for changes
gulp.task('watch', function () {
    gulp.watch(['src/**', 'test/**'], ['test']);

    var watchedMainBundler = watchify(mainBundler);
    watchedMainBundler.on('update', function () {
        rebundle(watchedMainBundler)
    });

    var watchedTestBundler = watchify(testBundler);
    watchedTestBundler.on('update', function () {
        rebundleTest(watchedTestBundler)
    });
});

gulp.task('default', ['verify', 'build', 'watch']);

/* START: build opendolphin tests  */

gulp.task('build-test:od', ['build:od'], function () {
    var bundle = browserify({debug: true})
        .add(glob.sync('./opendolphin/test*/**/*.ts'))
        .add('./opendolphin/testrunner/tsUnitKarmaAdapter.js')
        .plugin(tsify);

    return bundle.bundle()
        .on('error', $.util.log.bind($.util, 'Browserify Error'))
        .pipe(source('test-bundle.js'))
        .pipe(buffer())
        .pipe($.sourcemaps.init({loadMaps: true}))
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest('./opendolphin/test/build'));
});

/* END: build opendolphin tests  */

gulp.task('ci-common', ['build', 'build-test', 'build-test:od']);

//Test opendolphin
gulp.task('ci-test:od', ['ci-common'], function(done) {
    new Server({
        configFile: __dirname + '/opendolphin/testrunner/karma.conf.js',
        reporters: ['coverage'],
        singleRun: true
    }, done).start();
});

//Test dolphin-platform
gulp.task('ci-test', ['ci-common'], function (done) {
    new Server({
        configFile: __dirname + '/karma.conf.js',
        reporters: ['teamcity', 'coverage'],
        coverageReporter: {
            reporters: [
                {type: 'lcovonly', subdir: '.'}
            ]
        },
        singleRun: true
    }, done).start();
});

gulp.task('ci', ['ci-common', 'ci-test' , 'ci-test:od' ]);

// START: Saucelabs

function createSauceLabsTestStep(customLaunchers, browsers, done) {
    return function () {
        new Server({
            configFile: __dirname + '/karma.conf.js',
            customLaunchers: customLaunchers,
            browsers: browsers,
            reporters: ['saucelabs'],
            singleRun: true
        },function(result){
            if(result === 0){
                done();
            } else {
                process.exit(1);
            }
        }).start();
    }
}

function createSauceLabsTestPipe(customLaunchers, step) {
    // We cannot run too many instances at Sauce Labs in parallel, thus we need to run it several times
    // with only a few environments set
    var numSauceLabsVMs = 3;
    var allBrowsers = Object.keys(customLaunchers);

    while (allBrowsers.length > 0) {
        var browsers = [];
        for (var i = 0; i < numSauceLabsVMs && allBrowsers.length > 0; i++) {
            browsers.push(allBrowsers.shift());
        }

        step = createSauceLabsTestStep(customLaunchers, browsers, step);
    }

    step();
}

gulp.task('saucelabs', ['ci-common'], function (done) {
    var customLaunchers = require('./sauce.launchers.js').browsers;
    return createSauceLabsTestPipe(customLaunchers, done);
});
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const util = require('util')

const gulp         = require('gulp')
const autoprefixer = require('gulp-autoprefixer')
const clean_css    = require('gulp-clean-css')
const inject       = require('gulp-inject-string')
const less         = require('gulp-less')
const rename       = require('gulp-rename')
const sourcemaps   = require('gulp-sourcemaps')
const jsdom        = require('jsdom')
const kss          = require('kss')

const xjs          = require('extrajs-dom')
const {xDirectory,xPermalink} = require('aria-patterns')

const PACKAGE = require('./package.json')
const META = JSON.stringify({
  package: `https://www.npmjs.com/package/${PACKAGE.name}`,
  version: PACKAGE.version,
  license: PACKAGE.license,
  built  : new Date().toISOString(),
}, null, 2)

// HOW-TO: https://github.com/kss-node/kss-node/issues/161#issuecomment-222292620
gulp.task('docs-kss-markup', async function () {
  return kss(require('./config/kss.json'))
})

gulp.task('docs-kss-style', async function () {
  return gulp.src('./docs/css/kss-custom.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
    }))
    .pipe(gulp.dest('./docs/styleguide/'))
})

gulp.task('docs-kss', ['docs-kss-markup', 'docs-kss-style'])

gulp.task('docs-my-markup', async function () {
  const dom = new jsdom.JSDOM(await util.promisify(fs.readFile)(path.join(__dirname, './docs/tpl/index.tpl.html'), 'utf8'))
  const {document} = dom.window

  await (async function importLinks(relativepath) {
    if (!('import' in jsdom.JSDOM.fragment('<link rel="import" href="https://example.com/"/>').querySelector('link'))) {
      console.warn('`HTMLLinkElement#import` is not yet supported. Replacing `<link>`s with their imported contents.')
      return Promise.all(Array.from(document.querySelectorAll('link[rel~="import"][data-import]')).map(async function (link) {
        const import_switch = {
          'document': async () => jsdom.JSDOM.fragment(await util.promisify(fs.readFile)(path.resolve(relativepath, link.href), 'utf8')),
          'template': async () => (await xjs.HTMLTemplateElement.fromFile(path.resolve(relativepath, link.href))).content(),
          async default() { return null },
        }
        let imported = await (import_switch[link.getAttribute('data-import')] || import_switch.default).call(null)
        if (imported) {
          link.after(imported)
          link.remove() // link.href = path.resolve('https://example.com/index.html', link.href) // TODO set the href relative to the current window.location.href
        }
      }))
    } else return;
  })(path.resolve(__dirname, './docs/tpl/'))

  await Promise.all([
    (async function () {
      document.querySelector('#contents').append(xDirectory.render(require('./docs/index-toc.json')))
    })(),
    (async function () {
      const classname = {
        figure: 'docs-figure',
        pre   : 'docs-pre',
        code  : 'docs-code',
        form  : 'docs-form',
      }
      let fragment = (await xjs.HTMLTemplateElement.fromFile(path.resolve(__dirname, './docs/tpl/base.tpl.html'))).content().cloneNode(true)
      fragment.querySelectorAll([
        'section[id] > h2:first-of-type',
        'section[id] > h3:first-of-type',
        'section[id] > h4:first-of-type',
        'section[id] > h5:first-of-type',
        'section[id] > h6:first-of-type',
      ].join()).forEach(function (hn) {
        hn.append(xPermalink.render({ id: hn.parentNode.id }))
      })
      fragment.querySelectorAll(Object.keys(classname).join()).forEach(function (el) {
        let xel = new xjs.HTMLElement(el)
        if (classname[xel.tagName]) xel.addClass(classname[xel.tagName])
      })
      document.querySelector('main').append(fragment)
    })(),
  ])

  await util.promisify(fs.writeFile)(path.resolve(__dirname, './docs/index.html'), dom.serialize(), 'utf8')
})

gulp.task('docs-my-style', async function () {
  return gulp.src('docs/css/docs.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
    }))
    .pipe(gulp.dest('./docs/css/'))
})

gulp.task('docs-my', ['docs-my-markup', 'docs-my-style'])

gulp.task('docs', ['docs-kss', 'docs-my'])

gulp.task('dist', async function () {
  return gulp.src(['./css/src/*.less', '!./css/src/__*.less'])
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
    }))
    .pipe(clean_css({
      level: {
        2: {
          overrideProperties: false, // need fallbacks for `initial` and `unset`
          restructureRules: true, // combines selectors having the same rule (akin to `&:extend()`) // REVIEW be careful here
        },
      },
    }))
    .pipe(rename(function (p) {
      if (p.basename[0] === '_') {
        p.basename = p.basename.slice(1)
      }
    }))
    .pipe(inject.prepend(`/* ${META} */`))
    .pipe(sourcemaps.write('./')) // writes to an external .map file
    .pipe(gulp.dest('./css/dist/'))
})

gulp.task('build', ['docs', 'dist'])
<commit_msg>use xjs.Document#importLinksAsync()<commit_after>const fs = require('fs')
const path = require('path')
const util = require('util')

const gulp         = require('gulp')
const autoprefixer = require('gulp-autoprefixer')
const clean_css    = require('gulp-clean-css')
const inject       = require('gulp-inject-string')
const less         = require('gulp-less')
const rename       = require('gulp-rename')
const sourcemaps   = require('gulp-sourcemaps')
const jsdom        = require('jsdom')
const kss          = require('kss')

const xjs          = require('extrajs-dom')
const {xDirectory,xPermalink} = require('aria-patterns')

const PACKAGE = require('./package.json')
const META = JSON.stringify({
  package: `https://www.npmjs.com/package/${PACKAGE.name}`,
  version: PACKAGE.version,
  license: PACKAGE.license,
  built  : new Date().toISOString(),
}, null, 2)

// HOW-TO: https://github.com/kss-node/kss-node/issues/161#issuecomment-222292620
gulp.task('docs-kss-markup', async function () {
  return kss(require('./config/kss.json'))
})

gulp.task('docs-kss-style', async function () {
  return gulp.src('./docs/css/kss-custom.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
    }))
    .pipe(gulp.dest('./docs/styleguide/'))
})

gulp.task('docs-kss', ['docs-kss-markup', 'docs-kss-style'])

gulp.task('docs-my-markup', async function () {
  const dom = new jsdom.JSDOM(await util.promisify(fs.readFile)(path.join(__dirname, './docs/tpl/index.tpl.html'), 'utf8'))
  const {document} = dom.window

  await new xjs.Document(document).importLinksAsync(path.resolve(__dirname, './docs/tpl/'))

  await Promise.all([
    (async function () {
      document.querySelector('#contents').append(xDirectory.render(require('./docs/index-toc.json')))
    })(),
    (async function () {
      const classname = {
        figure: 'docs-figure',
        pre   : 'docs-pre',
        code  : 'docs-code',
        form  : 'docs-form',
      }
      let fragment = (await xjs.HTMLTemplateElement.fromFile(path.resolve(__dirname, './docs/tpl/base.tpl.html'))).content().cloneNode(true)
      fragment.querySelectorAll([
        'section[id] > h2:first-of-type',
        'section[id] > h3:first-of-type',
        'section[id] > h4:first-of-type',
        'section[id] > h5:first-of-type',
        'section[id] > h6:first-of-type',
      ].join()).forEach(function (hn) {
        hn.append(xPermalink.render({ id: hn.parentNode.id }))
      })
      fragment.querySelectorAll(Object.keys(classname).join()).forEach(function (el) {
        let xel = new xjs.HTMLElement(el)
        if (classname[xel.tagName]) xel.addClass(classname[xel.tagName])
      })
      document.querySelector('main').append(fragment)
    })(),
  ])

  await util.promisify(fs.writeFile)(path.resolve(__dirname, './docs/index.html'), dom.serialize(), 'utf8')
})

gulp.task('docs-my-style', async function () {
  return gulp.src('docs/css/docs.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
    }))
    .pipe(gulp.dest('./docs/css/'))
})

gulp.task('docs-my', ['docs-my-markup', 'docs-my-style'])

gulp.task('docs', ['docs-kss', 'docs-my'])

gulp.task('dist', async function () {
  return gulp.src(['./css/src/*.less', '!./css/src/__*.less'])
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
    }))
    .pipe(clean_css({
      level: {
        2: {
          overrideProperties: false, // need fallbacks for `initial` and `unset`
          restructureRules: true, // combines selectors having the same rule (akin to `&:extend()`) // REVIEW be careful here
        },
      },
    }))
    .pipe(rename(function (p) {
      if (p.basename[0] === '_') {
        p.basename = p.basename.slice(1)
      }
    }))
    .pipe(inject.prepend(`/* ${META} */`))
    .pipe(sourcemaps.write('./')) // writes to an external .map file
    .pipe(gulp.dest('./css/dist/'))
})

gulp.task('build', ['docs', 'dist'])
<|endoftext|>


<commit_before>const path = require('path');
const gulp = require('gulp');

const PACKAGE_NAME = require('./package.json').name;
const PACKAGES_PATH = './packages';
const DIST_PATH = './lib';
const DIST_PACKAGES_PATH = `${DIST_PATH}/packages`;
const ENTRY_FILE = 'entry.js';

const PACKAGE_PREFIX = /^decorator-/;

const isWin32 = (path.win32 === path);
const srcEx = isWin32 ? /(packages\\[^\\]+)\\src\\/ : /(packages\/[^\/]+)\/src\//;
const libFragment = isWin32 ? '$1\\lib\\' : '$1/lib/';

gulp.task('clean', (done) => {
	require('del')(DIST_PATH)
		.then(paths => {
			paths.forEach(path => console.log('delete: %s', path.replace(__dirname, '')));
			done();
		});
});

gulp.task('build:packages', () => {
	const plumber = require('gulp-plumber');
	const gutil = require('gulp-util');
	const newer = require('gulp-newer');
	const through = require('through2');
	const babel = require('gulp-babel');
	const chalk = require('chalk');

	return gulp.src(`${PACKAGES_PATH}/*/src/**/*.js`)
		.pipe(plumber({
			errorHandler(err) {
				gutil.log(err.stack);
			}
		}))
		.pipe(through.obj((file, enc, callback) => {
			file._path = file.path;
			file.path = file.path.replace(srcEx, libFragment);
			callback(null, file);
		}))
		.pipe(newer(PACKAGES_PATH))
		.pipe(through.obj((file, enc, callback) => {
			gutil.log('compiling', `'${chalk.cyan(file._path)}'...`);
			callback(null, file);
		}))
		.pipe(babel())
		.pipe(gulp.dest(PACKAGES_PATH));
});

gulp.task('build:modules', ['build:packages'], () => {
	return gulp.src([`${PACKAGES_PATH}/*/lib/**/*.js`, `${PACKAGES_PATH}/*/package.json`])
		.pipe(gulp.dest(DIST_PACKAGES_PATH));
});

gulp.task('entry', ['build:modules'], (done) => {
	const stream = require('stream');
	const pass = stream.PassThrough();
	const fs = require('fs');
	const makeVinylStream = require('vinyl-source-stream');

	fs.readdir(DIST_PACKAGES_PATH, (error, files) => {
		if (error) return console.error(error);
		const scripts = [];
		files.forEach((filename) => {
			if (PACKAGE_PREFIX) filename = filename.replace(PACKAGE_PREFIX, '');
			const key = filename.replace(/-([a-z])/g, (m, p1) => p1.toUpperCase());
			const script = `module.exports['${key}'] = require('./${filename}');`;
			scripts.push(script);
		});
		pass.end(new Buffer(scripts.join('\n'), 'utf8'));

		const out = pass.pipe(makeVinylStream(ENTRY_FILE))
			.pipe(gulp.dest(DIST_PACKAGES_PATH));

		done(null, out);
	});
});

gulp.task('build', ['entry'], () => {
	const browserify = require('browserify');
	const makeVinylStream = require('vinyl-source-stream');

	const options = {
		entries: [ENTRY_FILE],
		basedir: DIST_PACKAGES_PATH,
		standalone: PACKAGE_NAME
	};

	return browserify(options)
		.external(['react', 'react-dom', 'react/lib/PooledClass', 'lodash'])
		.bundle()
		.pipe(makeVinylStream(`${PACKAGE_NAME}.js`))
		.pipe(gulp.dest(DIST_PATH));
});

gulp.task('build:min', ['entry'], () => {
	const browserify = require('browserify');
	const makeVinylStream = require('vinyl-source-stream');
	const makeVinylBuffer = require('vinyl-buffer');
	const uglify = require('gulp-uglify');

	const derequire = require('browserify-derequire');
	const collapse = require('bundle-collapser/plugin');

	const options = {
		entries: [ENTRY_FILE],
		basedir: DIST_PACKAGES_PATH,
		standalone: PACKAGE_NAME,
		plugin: [derequire, collapse]
	};

	return browserify(options)
		.external(['react', 'react-dom', 'react/lib/PooledClass', 'lodash'])
		.bundle()
		.pipe(makeVinylStream(`${PACKAGE_NAME}.min.js`))
		.pipe(makeVinylBuffer())
		.pipe(uglify({
			compress: {
				if_return: true,
				dead_code: true,
				drop_console: true,
				drop_debugger: true
			},
			output: {
				ascii_only: true
			}
		}))
		.pipe(gulp.dest(DIST_PATH));
});

gulp.task('install-deps', (done) => {
	const pkgJSON = require('./package.json');
	console.log('where: ', pkgJSON._where);
	pkgJSON._where = pkgJSON._where || process.cwd();

	//require('check-deps')(pkgJSON, done);
	done('abc');
});

gulp.task('release', ['install-deps'], (done) => {
	const run = require('run-sequence');
	return run(
		'clean',
		['build', 'build:min'],
		done
	);
});

gulp.task('default', (done) => {
	const run = require('run-sequence');
	return run(
		'clean',
		'build',
		done
	);
});
<commit_msg>modify<commit_after>const path = require('path');
const gulp = require('gulp');

const PACKAGE_NAME = require('./package.json').name;
const PACKAGES_PATH = './packages';
const DIST_PATH = './lib';
const DIST_PACKAGES_PATH = `${DIST_PATH}/packages`;
const ENTRY_FILE = 'entry.js';

const PACKAGE_PREFIX = /^decorator-/;

const isWin32 = (path.win32 === path);
const srcEx = isWin32 ? /(packages\\[^\\]+)\\src\\/ : /(packages\/[^\/]+)\/src\//;
const libFragment = isWin32 ? '$1\\lib\\' : '$1/lib/';

gulp.task('clean', (done) => {
	require('del')(DIST_PATH)
		.then(paths => {
			paths.forEach(path => console.log('delete: %s', path.replace(__dirname, '')));
			done();
		});
});

gulp.task('build:packages', () => {
	const plumber = require('gulp-plumber');
	const gutil = require('gulp-util');
	const newer = require('gulp-newer');
	const through = require('through2');
	const babel = require('gulp-babel');
	const chalk = require('chalk');

	return gulp.src(`${PACKAGES_PATH}/*/src/**/*.js`)
		.pipe(plumber({
			errorHandler(err) {
				gutil.log(err.stack);
			}
		}))
		.pipe(through.obj((file, enc, callback) => {
			file._path = file.path;
			file.path = file.path.replace(srcEx, libFragment);
			callback(null, file);
		}))
		.pipe(newer(PACKAGES_PATH))
		.pipe(through.obj((file, enc, callback) => {
			gutil.log('compiling', `'${chalk.cyan(file._path)}'...`);
			callback(null, file);
		}))
		.pipe(babel())
		.pipe(gulp.dest(PACKAGES_PATH));
});

gulp.task('build:modules', ['build:packages'], () => {
	return gulp.src([`${PACKAGES_PATH}/*/lib/**/*.js`, `${PACKAGES_PATH}/*/package.json`])
		.pipe(gulp.dest(DIST_PACKAGES_PATH));
});

gulp.task('entry', ['build:modules'], (done) => {
	const stream = require('stream');
	const pass = stream.PassThrough();
	const fs = require('fs');
	const makeVinylStream = require('vinyl-source-stream');

	fs.readdir(DIST_PACKAGES_PATH, (error, files) => {
		if (error) return console.error(error);
		const scripts = [];
		files.forEach((filename) => {
			if (PACKAGE_PREFIX) filename = filename.replace(PACKAGE_PREFIX, '');
			const key = filename.replace(/-([a-z])/g, (m, p1) => p1.toUpperCase());
			const script = `module.exports['${key}'] = require('./${filename}');`;
			scripts.push(script);
		});
		pass.end(new Buffer(scripts.join('\n'), 'utf8'));

		const out = pass.pipe(makeVinylStream(ENTRY_FILE))
			.pipe(gulp.dest(DIST_PACKAGES_PATH));

		done(null, out);
	});
});

gulp.task('build', ['entry'], () => {
	const browserify = require('browserify');
	const makeVinylStream = require('vinyl-source-stream');

	const options = {
		entries: [ENTRY_FILE],
		basedir: DIST_PACKAGES_PATH,
		standalone: PACKAGE_NAME
	};

	return browserify(options)
		.external(['react', 'react-dom', 'react/lib/PooledClass', 'lodash'])
		.bundle()
		.pipe(makeVinylStream(`${PACKAGE_NAME}.js`))
		.pipe(gulp.dest(DIST_PATH));
});

gulp.task('build:min', ['entry'], () => {
	const browserify = require('browserify');
	const makeVinylStream = require('vinyl-source-stream');
	const makeVinylBuffer = require('vinyl-buffer');
	const uglify = require('gulp-uglify');

	const derequire = require('browserify-derequire');
	const collapse = require('bundle-collapser/plugin');

	const options = {
		entries: [ENTRY_FILE],
		basedir: DIST_PACKAGES_PATH,
		standalone: PACKAGE_NAME,
		plugin: [derequire, collapse]
	};

	return browserify(options)
		.external(['react', 'react-dom', 'react/lib/PooledClass', 'lodash'])
		.bundle()
		.pipe(makeVinylStream(`${PACKAGE_NAME}.min.js`))
		.pipe(makeVinylBuffer())
		.pipe(uglify({
			compress: {
				if_return: true,
				dead_code: true,
				drop_console: true,
				drop_debugger: true
			},
			output: {
				ascii_only: true
			}
		}))
		.pipe(gulp.dest(DIST_PATH));
});

gulp.task('install-deps', (done) => {
	const pkgJSON = require('./package.json');
	console.log('where: ', pkgJSON._where);
	pkgJSON._where = pkgJSON._where || process.cwd();

	require('check-deps')(pkgJSON, done);
	//done('abc');
});

gulp.task('release', ['install-deps'], (done) => {
	const run = require('run-sequence');
	return run(
		'clean',
		['build', 'build:min'],
		done
	);
});

gulp.task('default', (done) => {
	const run = require('run-sequence');
	return run(
		'clean',
		'build',
		done
	);
});
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    less = require('gulp-less'),
    sass = require('gulp-sass'),
    browserSync = require('browser-sync').create(),
    header = require('gulp-header'),
    cleanCSS = require('gulp-clean-css'),
    rename = require("gulp-rename"),
    replace = require('gulp-replace'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    maps = require('gulp-sourcemaps'),
    pkg = require('./package.json');

// Set the banner content
var banner = ['/*!\n',
    ' * Start Bootstrap - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n',
    ' * Copyright 2013-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n',
    ' * Licensed under <%= pkg.license %>\n',
    ' */\n',
    ''
].join('');

// Compile LESS files from /less into /css
gulp.task('less', function() {
    return gulp.src('less/agency.less')
        .pipe(less())
        .pipe(header(banner, { pkg: pkg }))
        .pipe(gulp.dest('css'))
        .pipe(browserSync.reload({
            stream: true
        }));
});

// Concatenate CSS
gulp.task('concat-css', ['less'], function(){
	return gulp.src(['vendor/bootstrap/css/bootstrap.min.css',
		'vendor/font-awesome/css/font-awesome.min.css',
		'https://fonts.googleapis.com/css?family=Montserrat:400,700',
		'https://fonts.googleapis.com/css?family=Kaushan+Script',
		'https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic',
		'https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700',
		'css/agency.css',
        'css/sean.css'])
		.pipe(maps.init())
		.pipe(concat('main.css'))
		.pipe(maps.write('./'))
    	.pipe(gulp.dest("css"))
    	.pipe(browserSync.reload({
            stream: true
        }));
});

// Minify compiled CSS
gulp.task('minify-css', ['concat-css'], function() {
    return gulp.src('css/main.css')
        .pipe(cleanCSS({ compatibility: 'ie8' }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('css'))
        .pipe(browserSync.reload({
            stream: true
        }));
});

// Concatenate JS
gulp.task('concat-js', function(){
	return gulp.src(['vendor/jquery/jquery.min.js',
		'vendor/bootstrap/js/bootstrap.min.js',
		'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js',
		'js/jqBootstrapValidation.js',
		'js/contact_me.js',
		'js/agency.js',
        'js/sean.js'])
		.pipe(maps.init())
		.pipe(concat('main.js'))
		.pipe(maps.write('./'))
    	.pipe(gulp.dest("js"))
    	.pipe(browserSync.reload({
            stream: true
        }));
});

// Minify JS
gulp.task('minify-js', ['concat-js'], function() {
    return gulp.src('js/main.js')
        .pipe(uglify())
        .pipe(header(banner, { pkg: pkg }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('js'))
        .pipe(browserSync.reload({
            stream: true
        }));
});

// Create html
gulp.task('dev-html', function(){
	return gulp.src('index.template')
		.pipe(replace('{{STYLE}}', 'css/main.css'))
		.pipe(replace('{{SCRIPT}}', 'js/main.js'))
		.pipe(rename('index.html'))
		.pipe(gulp.dest('./'))
		.pipe(browserSync.reload({
            stream: true
        }));
});

// Copy vendor libraries from /node_modules into /vendor
gulp.task('copy', function() {
    gulp.src(['node_modules/bootstrap/dist/**/*', '!**/npm.js', '!**/bootstrap-theme.*', '!**/*.map'])
        .pipe(gulp.dest('vendor/bootstrap'))

    gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js'])
        .pipe(gulp.dest('vendor/jquery'))

    gulp.src([
            'node_modules/font-awesome/**',
            '!node_modules/font-awesome/**/*.map',
            '!node_modules/font-awesome/.npmignore',
            '!node_modules/font-awesome/*.txt',
            '!node_modules/font-awesome/*.md',
            '!node_modules/font-awesome/*.json'
        ])
        .pipe(gulp.dest('vendor/font-awesome'));
    gulp.src(['node_modules/font-awesome/fonts/*'])
    	.pipe(gulp.dest('fonts'));
})

// Run everything
gulp.task('default', ['less', 'minify-css', 'minify-js', 'copy']);

// Configure the browserSync task
gulp.task('browserSync', function() {
    browserSync.init({
        server: {
            baseDir: ''
        },
    });
})

// Dev task with browserSync
gulp.task('dev', ['browserSync', 'less', 'minify-css', 'minify-js', 'dev-html', 'copy'], function() {
    gulp.watch('less/*.less', ['less']);
    gulp.watch('css/*.css', ['minify-css']);
    gulp.watch('js/*.js', ['minify-js']);
    gulp.watch('index.template', ['dev-html']);
    // Reloads the browser whenever HTML or JS files change
    gulp.watch('*.html', browserSync.reload);
    gulp.watch('js/**/*.js', browserSync.reload);
});
<commit_msg>add initial critical POC task<commit_after>var gulp = require('gulp'),
    less = require('gulp-less'),
    sass = require('gulp-sass'),
    browserSync = require('browser-sync').create(),
    header = require('gulp-header'),
    cleanCSS = require('gulp-clean-css'),
    rename = require("gulp-rename"),
    replace = require('gulp-replace'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    maps = require('gulp-sourcemaps'),
    pkg = require('./package.json'),
    gutil = require('gulp-util'),
    critical = require('critical').stream;

// Set the banner content
var banner = ['/*!\n',
    ' * Start Bootstrap - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n',
    ' * Copyright 2013-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n',
    ' * Licensed under <%= pkg.license %>\n',
    ' */\n',
    ''
].join('');

// Compile LESS files from /less into /css
gulp.task('less', function() {
    return gulp.src('less/agency.less')
        .pipe(less())
        .pipe(header(banner, { pkg: pkg }))
        .pipe(gulp.dest('css'))
        .pipe(browserSync.reload({
            stream: true
        }));
});

// Concatenate CSS
gulp.task('concat-css', ['less'], function(){
	return gulp.src(['vendor/bootstrap/css/bootstrap.min.css',
		'vendor/font-awesome/css/font-awesome.min.css',
		'https://fonts.googleapis.com/css?family=Montserrat:400,700',
		'https://fonts.googleapis.com/css?family=Kaushan+Script',
		'https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic',
		'https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700',
		'css/agency.css',
        'css/sean.css'])
		.pipe(maps.init())
		.pipe(concat('main.css'))
		.pipe(maps.write('./'))
    	.pipe(gulp.dest("css"))
    	.pipe(browserSync.reload({
            stream: true
        }));
});

// Minify compiled CSS
gulp.task('minify-css', ['concat-css'], function() {
    return gulp.src('css/main.css')
        .pipe(cleanCSS({ compatibility: 'ie8' }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('css'))
        .pipe(browserSync.reload({
            stream: true
        }));
});

// Concatenate JS
gulp.task('concat-js', function(){
	return gulp.src(['vendor/jquery/jquery.min.js',
		'vendor/bootstrap/js/bootstrap.min.js',
		'js/jqBootstrapValidation.js',
		'js/contact_me.js',
		'js/agency.js',
        'js/sean.js'])
		.pipe(maps.init())
		.pipe(concat('main.js'))
		.pipe(maps.write('./'))
    	.pipe(gulp.dest("js"))
    	.pipe(browserSync.reload({
            stream: true
        }));
});

// Minify JS
gulp.task('minify-js', ['concat-js'], function() {
    return gulp.src('js/main.js')
        .pipe(uglify())
        .pipe(header(banner, { pkg: pkg }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('js'))
        .pipe(browserSync.reload({
            stream: true
        }));
});

// Create html
gulp.task('dev-html', function(){
	return gulp.src('index.template')
		.pipe(replace('{{STYLE}}', 'css/main.css'))
		.pipe(replace('{{SCRIPT}}', 'js/main.js'))
		.pipe(rename('index.html'))
		.pipe(gulp.dest('./'))
		.pipe(browserSync.reload({
            stream: true
        }));
});

//critical css
gulp.task('critical', function () {
    return gulp.src('index.html')
        .pipe(critical({base: 'dist/', inline: true, css: ['css/main.min.css']}))
        .on('error', function(err) { gutil.log(gutil.colors.red(err.message)); })
        .pipe(gulp.dest('dist'));
});

// Copy vendor libraries from /node_modules into /vendor
gulp.task('copy', function() {
    gulp.src(['node_modules/bootstrap/dist/**/*', '!**/npm.js', '!**/bootstrap-theme.*', '!**/*.map'])
        .pipe(gulp.dest('vendor/bootstrap'))

    gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js'])
        .pipe(gulp.dest('vendor/jquery'))

    gulp.src([
            'node_modules/font-awesome/**',
            '!node_modules/font-awesome/**/*.map',
            '!node_modules/font-awesome/.npmignore',
            '!node_modules/font-awesome/*.txt',
            '!node_modules/font-awesome/*.md',
            '!node_modules/font-awesome/*.json'
        ])
        .pipe(gulp.dest('vendor/font-awesome'));
    gulp.src(['node_modules/font-awesome/fonts/*'])
    	.pipe(gulp.dest('fonts'));
})

// Run everything
gulp.task('default', ['less', 'minify-css', 'minify-js', 'copy']);

// Configure the browserSync task
gulp.task('browserSync', function() {
    browserSync.init({
        server: {
            baseDir: ''
        },
    });
})

// Dev task with browserSync
gulp.task('dev', ['browserSync', 'less', 'minify-css', 'minify-js', 'dev-html', 'copy'], function() {
    gulp.watch('less/*.less', ['less']);
    gulp.watch('css/*.css', ['minify-css']);
    gulp.watch('js/*.js', ['minify-js']);
    gulp.watch('index.template', ['dev-html']);
    // Reloads the browser whenever HTML or JS files change
    gulp.watch('*.html', browserSync.reload);
    gulp.watch('js/**/*.js', browserSync.reload);
});
<|endoftext|>


<commit_before>/**
 * gulpfile for colony
 *
 * Here are the common tasks used:
 * build
 * - Lint and compile
 * - (default Grunt task)
 * test
 *  - Run all tests
 * jsdoc
 *  - Generate jsdoc documentation
 **/
var gulp = require("gulp");
var gulpSequence = require("gulp-sequence");
var fs = require("fs-extra");
var jshint = require("gulp-jshint");
var browserify = require("browserify");
var source = require("vinyl-source-stream");
var buffer = require("vinyl-buffer");
var pkgify = require("pkgify");
var path = require("path");
var spawn = require("child_process").spawn;

gulp.task("build_digitalocean", function() {
  "use strict";
  var entry = require.resolve("digitalocean-api");
  var filename = path.basename(entry);
  var bundle = function() {
    return browserify({
      entries: [ entry ],
      debug: true
    }).transform(pkgify, {
      packages: {
        request: path.relative(__dirname, require.resolve("browser-request"))
      },
      relativeTo: __dirname
    }).bundle()
      .pipe(source(filename))
      .pipe(buffer())
      .pipe(gulp.dest("./client/build/www/build/"));
  };
  return bundle();
});

gulp.task("lint", function() {
  "use strict";
  return gulp.src([
      "*.json",
      "client/common/**/*.js",
    ]).pipe(jshint({ lookup: true }))
    .pipe(jshint.reporter("default"));
});

var cordovaTask = function(args, cb) {
  var proc = spawn(require.resolve("cordova/bin/cordova"), args, {
    cwd: "client/build"
  });
  proc.stdout.on('data', function (data) {
    console.log(data.toString().trim());
  });
  proc.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
  });
  proc.on('close', function (code) {
    console.log('child process exited with code ' + code);
    cb(code);
  });
};

gulp.task("cordova_create", function(cb) {
  spawn(
    require.resolve("cordova/bin/cordova"),
    [ "create", "build", "org.uproxy.colony", "Colony" ],
    { cwd: "client" }
  ).on("close", function(code) { cb(); })
});
gulp.task("cordova_platform_android", cordovaTask.bind({}, [ "platform", "add", "android" ]));
gulp.task("cordova_plugin_oauthredirect", cordovaTask.bind({}, [ "plugin", "add", "../plugins/cordova-plugin-oauthredirect/" ]));
gulp.task("cordova_build", cordovaTask.bind({}, [ "build" ]));
gulp.task("cordova_emulate", cordovaTask.bind({}, [ "emulate", "android" ]));
gulp.task("setup_www", function(cb) {
  fs.copy("client/www/*", "client/build/www/", cb);
});
gulp.task("clean", function(cb) {
  fs.remove("client/build", function() { cb(); });
});

gulp.task("build", gulpSequence(
  "cordova_create",
  "cordova_platform_android",
  "cordova_plugin_oauthredirect",
  "setup_www",
  "build_digitalocean",
  "cordova_build",
  "cordova_emulate"
));
gulp.task("test", [ "lint" ]);
gulp.task("default", [ "build", "test" ]);
<commit_msg>reverting some gulpfile changes<commit_after>/**
 * gulpfile for colony
 *
 * Here are the common tasks used:
 * build
 * - Lint and compile
 * - (default Grunt task)
 * test
 *  - Run all tests
 * jsdoc
 *  - Generate jsdoc documentation
 **/
var gulp = require("gulp");
var gulpSequence = require("gulp-sequence");
var fs = require("fs-extra");
var jshint = require("gulp-jshint");
var browserify = require("browserify");
var source = require("vinyl-source-stream");
var buffer = require("vinyl-buffer");
var pkgify = require("pkgify");
var path = require("path");
var spawn = require("child_process").spawn;

gulp.task("build_digitalocean", function() {
  "use strict";
  var entry = require.resolve("digitalocean-api");
  var filename = path.basename(entry);
  var bundle = function() {
    return browserify({
      entries: [ entry ],
      debug: true
    }).transform(pkgify, {
      packages: {
        request: path.relative(__dirname, require.resolve("browser-request"))
      },
      relativeTo: __dirname
    }).bundle()
      .pipe(source(filename))
      .pipe(buffer())
      .pipe(gulp.dest("./client/www/build/"));
  };
  return bundle();
});

gulp.task("lint", function() {
  "use strict";
  return gulp.src([
      "*.json",
      "client/common/**/*.js",
    ]).pipe(jshint({ lookup: true }))
    .pipe(jshint.reporter("default"));
});

/**
var cordovaTask = function(args, cb) {
  var proc = spawn(require.resolve("cordova/bin/cordova"), args, {
    cwd: "client/build"
  });
  proc.stdout.on('data', function (data) {
    console.log(data.toString().trim());
  });
  proc.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
  });
  proc.on('close', function (code) {
    console.log('child process exited with code ' + code);
    cb(code);
  });
};
gulp.task("cordova_create", function(cb) {
  spawn(
    require.resolve("cordova/bin/cordova"),
    [ "create", "build", "org.uproxy.colony", "Colony" ],
    { cwd: "client" }
  ).on("close", function(code) { cb(); })
});
gulp.task("cordova_platform_android", cordovaTask.bind({}, [ "platform", "add", "android" ]));
gulp.task("cordova_plugin_oauthredirect", cordovaTask.bind({}, [ "plugin", "add", "../plugins/cordova-plugin-oauthredirect/" ]));
gulp.task("cordova_build", cordovaTask.bind({}, [ "build" ]));
gulp.task("cordova_emulate", cordovaTask.bind({}, [ "emulate", "android" ]));
gulp.task("setup_www", function(cb) {
  fs.copy("client/www/*", "client/build/www/", cb);
});
gulp.task("clean", function(cb) {
  fs.remove("client/build", function() { cb(); });
});

gulp.task("build", gulpSequence(
  "cordova_create",
  "cordova_platform_android",
  "cordova_plugin_oauthredirect",
  "setup_www",
  "build_digitalocean",
  "cordova_build",
  "cordova_emulate"
));
**/
gulp.task("build", [ "build_digitalocean" ]);
gulp.task("test", [ "lint" ]);
gulp.task("default", [ "build", "test" ]);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var tinylr = require('tiny-lr');

gulp.task('watch', () => {
  var lr = tinylr();
  lr.listen(35729, () => {
    console.log('... LiveReload on localhost:35729\n');
  });
  gulp.watch(['index.html', 'js/**/*', 'css/**/*'], evt => {
    console.log(evt.path);
    lr.changed({
      body: {
        files: [evt.path]
      }
    });
  });
});
<commit_msg>removed ;<commit_after>var gulp = require('gulp')
var tinylr = require('tiny-lr')

gulp.task('watch', () => {
  var lr = tinylr()
  lr.listen(35729, () => {
    console.log('... LiveReload on localhost:35729\n')
  })
  gulp.watch(['index.html', 'js/**/*', 'css/**/*'], evt => {
    console.log(evt.path)
    lr.changed({
      body: {
        files: [evt.path]
      }
    })
  })
})
<|endoftext|>