<commit_before>import { render as preactRender, cloneElement as preactCloneElement, createRef, createElement as h, Component, options, toChildArray } from 'ceviche';

const version = '15.1.0'; // trick libraries to think we are react

const REACT_ELEMENT_TYPE = (typeof Symbol!=='undefined' && Symbol.for && Symbol.for('react.element')) || 0xeac7;

const CAMEL_PROPS = /^(?:accent|alignment|arabic|baseline|cap|clip|color|fill|flood|font|glyph|horiz|marker|overline|paint|stop|strikethrough|stroke|text|underline|unicode|units|v|vector|vert|word|writing|x)[A-Z]/;

let oldEventHook = options.event;
options.event = e => {
	if (oldEventHook) e = oldEventHook(e);
	e.persist = Object;
	e.nativeEvent = e;
	return e;
};

function handleElementVNode(vnode, a) {
	let shouldSanitize, attrs, i;
	if (a) {
		for (i in a) if ((shouldSanitize = CAMEL_PROPS.test(i))) break;
		if (shouldSanitize) {
			attrs = vnode.props = {};
			for (i in a) {
				if (a.hasOwnProperty(i)) {
					attrs[ CAMEL_PROPS.test(i) ? i.replace(/([A-Z0-9])/, '-$1').toLowerCase() : i ] = a[i];
				}
			}
		}
	}
}

// proxy render() since React returns a Component reference.
function render(vnode, parent, callback) {
	preactRender(vnode, parent);
	if (typeof callback==='function') callback();

	return vnode!=null ? vnode._component : null;
}

class ContextProvider {
	getChildContext() {
		return this.props.context;
	}
	render(props) {
		return props.children;
	}
}

function renderSubtreeIntoContainer(parentComponent, vnode, container, callback) {
	let wrap = h(ContextProvider, { context: parentComponent.context }, vnode);
	let rendered = render(wrap, container);
	let c = rendered.props.children._component;
	if (callback) callback.call(c, rendered);
	return c;
}

function Portal(props) {
	renderSubtreeIntoContainer(this, props.vnode, props.container);
}

function createPortal(vnode, container) {
	return h(Portal, { vnode, container });
}

const mapFn = (children, fn, ctx) => {
	if (children == null) return null;
	children = toChildArray(children);
	if (ctx && ctx!==children) fn = fn.bind(ctx);
	return children.map(fn);
};

// This API is completely unnecessary for Preact, so it's basically passthrough.
let Children = {
	map: mapFn,
	forEach: mapFn,
	count(children) {
		return children ? toChildArray(children).length : 0;
	},
	only(children) {
		children = toChildArray(children);
		if (children.length!==1) throw new Error('Children.only() expects only one child.');
		return children[0];
	},
	toArray: toChildArray
};

function upgradeToVNodes(arr, offset) {
	for (let i=offset || 0; i<arr.length; i++) {
		let obj = arr[i];
		if (Array.isArray(obj)) {
			upgradeToVNodes(obj);
		}
		else if (obj && typeof obj==='object' && !isValidElement(obj) && ((obj.props && obj.type) || obj.props || obj.children)) {
			arr[i] = createElement(obj.type, obj.props, obj.children);
		}
	}
}

function createElement(...args) {
	upgradeToVNodes(args, 2);
	let vnode = h(...args);
	vnode.$$typeof = REACT_ELEMENT_TYPE;

	let type = vnode.type, props = vnode.props;
	if (typeof type==='function') {
		if ((type.prototype && 'isReactComponent' in type.prototype) && !vnode.preactCompatNormalized) {
			normalizeVNode(vnode);
		}
	}
	else {
		if (props.defaultValue) {
			if (!props.value && props.value!==0) {
				props.value = props.defaultValue;
			}
			delete props.defaultValue;
		}

		handleElementVNode(vnode, props);
	}

	vnode.preactCompatNormalized = false;
	return normalizeVNode(vnode);
}

function normalizeVNode(vnode) {
	vnode.preactCompatNormalized = true;
	applyClassName(vnode);
	applyEventNormalization(vnode);
	return vnode;
}

function cloneElement(element) {
	if (!isValidElement(element)) return element;
	let vnode = normalizeVNode(preactCloneElement.apply(null, arguments));
	vnode.$$typeof = REACT_ELEMENT_TYPE;
	return vnode;
}

function isValidElement(element) {
	return element && element.$$typeof===REACT_ELEMENT_TYPE;
}

function applyEventNormalization({ type, props }) {
	if (!props || typeof type!=='string') return;
	let newProps = {};
	for (let i in props) {
		newProps[i.toLowerCase()] = i;
	}
	if (newProps.ondoubleclick) {
		props.ondblclick = props[newProps.ondoubleclick];
		delete props[newProps.ondoubleclick];
	}
	// for *textual inputs* (incl textarea), normalize `onChange` -> `onInput`:
	if (newProps.onchange && (type==='textarea' || (type.toLowerCase()==='input' && !/^fil|che|rad/i.test(props.type)))) {
		let normalized = newProps.oninput || 'oninput';
		if (!props[normalized]) {
			props[normalized] = props[newProps.onchange];
			delete props[newProps.onchange];
		}
	}
}

function applyClassName(vnode) {
	let a = vnode.props;
	if (a.class || a.className) {
		classNameDescriptor.enumerable = 'className' in a;
		if (a.className) a.class = a.className;
		Object.defineProperty(a, 'className', classNameDescriptor);
	}
}

let classNameDescriptor = {
	configurable: true,
	get() { return this.class; },
	set(v) { this.class = v; }
};

function shallowDiffers(a, b) {
	for (let i in a) if (!(i in b)) return true;
	for (let i in b) if (a[i]!==b[i]) return true;
	return false;
}

function findDOMNode(component) {
	return component && (component.base || component.nodeType === 1 && component) || null;
}

function PureComponent(props, context) {
	Component.call(this, props, context);
}
PureComponent.prototype = Object.create(Component.prototype);
PureComponent.prototype.isPureReactComponent = true;
PureComponent.prototype.shouldComponentUpdate = function(props, state) {
	return shallowDiffers(this.props, props) || shallowDiffers(this.state, state);
};

export {
	version,
	Children,
	render,
	render as hydrate,
	createPortal,
	createElement,
	cloneElement,
	createRef,
	isValidElement,
	findDOMNode,
	Component,
	PureComponent
};

export default {
	version,
	Children,
	render,
	hydrate: render,
	createPortal,
	createElement,
	cloneElement,
	createRef,
	isValidElement,
	findDOMNode,
	Component,
	PureComponent
};
<commit_msg>Inline portal code<commit_after>import { render as preactRender, cloneElement as preactCloneElement, createRef, createElement as h, Component, options, toChildArray } from 'ceviche';

const version = '15.1.0'; // trick libraries to think we are react

const REACT_ELEMENT_TYPE = (typeof Symbol!=='undefined' && Symbol.for && Symbol.for('react.element')) || 0xeac7;

const CAMEL_PROPS = /^(?:accent|alignment|arabic|baseline|cap|clip|color|fill|flood|font|glyph|horiz|marker|overline|paint|stop|strikethrough|stroke|text|underline|unicode|units|v|vector|vert|word|writing|x)[A-Z]/;

let oldEventHook = options.event;
options.event = e => {
	if (oldEventHook) e = oldEventHook(e);
	e.persist = Object;
	e.nativeEvent = e;
	return e;
};

function handleElementVNode(vnode, a) {
	let shouldSanitize, attrs, i;
	if (a) {
		for (i in a) if ((shouldSanitize = CAMEL_PROPS.test(i))) break;
		if (shouldSanitize) {
			attrs = vnode.props = {};
			for (i in a) {
				if (a.hasOwnProperty(i)) {
					attrs[ CAMEL_PROPS.test(i) ? i.replace(/([A-Z0-9])/, '-$1').toLowerCase() : i ] = a[i];
				}
			}
		}
	}
}

// proxy render() since React returns a Component reference.
function render(vnode, parent, callback) {
	preactRender(vnode, parent);
	if (typeof callback==='function') callback();

	return vnode!=null ? vnode._component : null;
}

class ContextProvider {
	getChildContext() {
		return this.props.context;
	}
	render(props) {
		return props.children;
	}
}

function Portal(props) {
	let wrap = h(ContextProvider, { context: this.context }, props.vnode);
	let rendered = render(wrap, props.container);
	return rendered.props.children._component;
}

function createPortal(vnode, container) {
	return h(Portal, { vnode, container });
}

const mapFn = (children, fn, ctx) => {
	if (children == null) return null;
	children = toChildArray(children);
	if (ctx && ctx!==children) fn = fn.bind(ctx);
	return children.map(fn);
};

// This API is completely unnecessary for Preact, so it's basically passthrough.
let Children = {
	map: mapFn,
	forEach: mapFn,
	count(children) {
		return children ? toChildArray(children).length : 0;
	},
	only(children) {
		children = toChildArray(children);
		if (children.length!==1) throw new Error('Children.only() expects only one child.');
		return children[0];
	},
	toArray: toChildArray
};

function upgradeToVNodes(arr, offset) {
	for (let i=offset || 0; i<arr.length; i++) {
		let obj = arr[i];
		if (Array.isArray(obj)) {
			upgradeToVNodes(obj);
		}
		else if (obj && typeof obj==='object' && !isValidElement(obj) && ((obj.props && obj.type) || obj.props || obj.children)) {
			arr[i] = createElement(obj.type, obj.props, obj.children);
		}
	}
}

function createElement(...args) {
	upgradeToVNodes(args, 2);
	let vnode = h(...args);
	vnode.$$typeof = REACT_ELEMENT_TYPE;

	let type = vnode.type, props = vnode.props;
	if (typeof type==='function') {
		if ((type.prototype && 'isReactComponent' in type.prototype) && !vnode.preactCompatNormalized) {
			normalizeVNode(vnode);
		}
	}
	else {
		if (props.defaultValue) {
			if (!props.value && props.value!==0) {
				props.value = props.defaultValue;
			}
			delete props.defaultValue;
		}

		handleElementVNode(vnode, props);
	}

	vnode.preactCompatNormalized = false;
	return normalizeVNode(vnode);
}

function normalizeVNode(vnode) {
	vnode.preactCompatNormalized = true;
	applyClassName(vnode);
	applyEventNormalization(vnode);
	return vnode;
}

function cloneElement(element) {
	if (!isValidElement(element)) return element;
	let vnode = normalizeVNode(preactCloneElement.apply(null, arguments));
	vnode.$$typeof = REACT_ELEMENT_TYPE;
	return vnode;
}

function isValidElement(element) {
	return element && element.$$typeof===REACT_ELEMENT_TYPE;
}

function applyEventNormalization({ type, props }) {
	if (!props || typeof type!=='string') return;
	let newProps = {};
	for (let i in props) {
		newProps[i.toLowerCase()] = i;
	}
	if (newProps.ondoubleclick) {
		props.ondblclick = props[newProps.ondoubleclick];
		delete props[newProps.ondoubleclick];
	}
	// for *textual inputs* (incl textarea), normalize `onChange` -> `onInput`:
	if (newProps.onchange && (type==='textarea' || (type.toLowerCase()==='input' && !/^fil|che|rad/i.test(props.type)))) {
		let normalized = newProps.oninput || 'oninput';
		if (!props[normalized]) {
			props[normalized] = props[newProps.onchange];
			delete props[newProps.onchange];
		}
	}
}

function applyClassName(vnode) {
	let a = vnode.props;
	if (a.class || a.className) {
		classNameDescriptor.enumerable = 'className' in a;
		if (a.className) a.class = a.className;
		Object.defineProperty(a, 'className', classNameDescriptor);
	}
}

let classNameDescriptor = {
	configurable: true,
	get() { return this.class; },
	set(v) { this.class = v; }
};

function shallowDiffers(a, b) {
	for (let i in a) if (!(i in b)) return true;
	for (let i in b) if (a[i]!==b[i]) return true;
	return false;
}

function findDOMNode(component) {
	return component && (component.base || component.nodeType === 1 && component) || null;
}

function PureComponent(props, context) {
	Component.call(this, props, context);
}
PureComponent.prototype = Object.create(Component.prototype);
PureComponent.prototype.isPureReactComponent = true;
PureComponent.prototype.shouldComponentUpdate = function(props, state) {
	return shallowDiffers(this.props, props) || shallowDiffers(this.state, state);
};

export {
	version,
	Children,
	render,
	render as hydrate,
	createPortal,
	createElement,
	cloneElement,
	createRef,
	isValidElement,
	findDOMNode,
	Component,
	PureComponent
};

export default {
	version,
	Children,
	render,
	hydrate: render,
	createPortal,
	createElement,
	cloneElement,
	createRef,
	isValidElement,
	findDOMNode,
	Component,
	PureComponent
};
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var babel = require('gulp-babel');
var eslint = require('gulp-eslint');
var plugins = require('gulp-load-plugins')();

var fs = require('fs');
var path = require('path');
var es = require('event-stream');
var rename = require('gulp-rename');

var moduleName = (function() {
  var args = process.argv;
  var length = args.length;
  var i = 0;
  var name;
  var subName;
  var useSubName;

  while (i++ < length) {
    if (/^--+(\w+)/i.test(args[i])) {
      name = args[i].split('--')[1];
      subName = args[i].split('--')[2];
      useSubName = args[i].split('--')[3];
      break;
    }
  }
  return {
    name: name,
    subName: subName,
    useSubName: useSubName
  };
})();

// Admin Module
// Command: gulp [task]
// Admin is default task
// Watch Admin module: gulp
// -----------------------------------------------------------------------------

function adminTasks() {
  var pathto = function(file) {
    return '../admin/views/assets/' + file;
  };
  var scripts = {
    src: pathto('javascripts/app/*.js'),
    dest: pathto('javascripts'),
    qor: pathto('javascripts/qor/*.js'),
    qorInit: pathto('javascripts/qor/qor-config.js'),
    qorCommon: pathto('javascripts/qor/qor-common.js'),
    qorAdmin: [pathto('javascripts/qor.js'), pathto('javascripts/app.js')],
    all: ['gulpfile.js', pathto('javascripts/qor/*.js')]
  };
  var styles = {
    src: pathto('stylesheets/scss/{app,qor}.scss'),
    dest: pathto('stylesheets'),
    vendors: pathto('stylesheets/vendors'),
    main: pathto('stylesheets/{qor,app}.css'),
    qorAdmin: [pathto('stylesheets/vendors.css'), pathto('stylesheets/qor.css'), pathto('stylesheets/app.css')],
    scss: pathto('stylesheets/scss/**/*.scss')
  };

  gulp.task('qor', function() {
    return gulp
      .src([scripts.qorInit, scripts.qorCommon, scripts.qor])
      .pipe(plugins.concat('qor.js'))
      .pipe(plugins.uglify())
      .pipe(gulp.dest(scripts.dest));
  });

  gulp.task('js', ['qor'], function() {
    return gulp
      .src(scripts.src)
      .pipe(
        eslint({
          configFile: '.eslintrc'
        })
      )
      .pipe(plugins.concat('app.js'))
      .pipe(plugins.uglify())
      .pipe(gulp.dest(scripts.dest));
  });

  gulp.task('qor+', function() {
    return gulp
      .src([scripts.qorInit, scripts.qorCommon, scripts.qor])
      .pipe(
        eslint({
          configFile: '.eslintrc'
        })
      )
      .pipe(
        babel({
          presets: ['es2015']
        })
      )
      .pipe(eslint.format())
      .pipe(plugins.concat('qor.js'))
      .pipe(plugins.uglify())
      .pipe(gulp.dest(scripts.dest));
  });

  gulp.task('js+', function() {
    return gulp
      .src(scripts.src)
      .pipe(
        babel({
          presets: ['es2015']
        })
      )
      .pipe(eslint.format())
      .pipe(plugins.concat('app.js'))
      .pipe(plugins.uglify())
      .pipe(gulp.dest(scripts.dest));
  });

  gulp.task('sass', function() {
    return gulp.src(styles.src).pipe(plugins.sass()).pipe(gulp.dest(styles.dest));
  });

  gulp.task('css', ['sass'], function() {
    return gulp
      .src(styles.main)
      .pipe(plugins.autoprefixer())
      .pipe(plugins.csscomb())
      .pipe(plugins.minifyCss())
      .pipe(gulp.dest(styles.dest));
  });

  gulp.task('release_js', function() {
    return gulp.src(scripts.qorAdmin).pipe(plugins.concat('qor-admin.js')).pipe(gulp.dest(scripts.dest));
  });

  gulp.task('release_css', function() {
    return gulp.src(styles.qorAdmin).pipe(plugins.concat('qor-admin.css')).pipe(gulp.dest(styles.dest));
  });

  gulp.task('release', ['qor+', 'js+', 'css', 'release_js', 'release_css']);

  var watcher = gulp.task('watch', function() {
    var watch_qor = gulp.watch(scripts.qor, ['qor+']);
    var watch_js = gulp.watch(scripts.src, ['js+']);
    var watch_css = gulp.watch(styles.scss, ['css']);

    gulp.watch(styles.qorAdmin, ['release_css']);
    gulp.watch(scripts.qorAdmin, ['release_js']);

    watch_qor.on('change', function(event) {
      console.log(':==> File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
    watch_js.on('change', function(event) {
      console.log(':==> File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
    watch_css.on('change', function(event) {
      console.log(':==> File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
  });

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

// -----------------------------------------------------------------------------
// Other Modules
// Command: gulp [task] --moduleName--subModuleName
//
//  example:
// Watch Worker module: gulp --worker
//
// if module's assets just as normal path:
// moduleName/views/themes/moduleName/assets/javascripts(stylesheets)
// just use gulp --worker
//
// if module's assets in enterprise as normal path:
// moduleName/views/themes/moduleName/assets/javascripts(stylesheets)
// just use gulp --microsite--enterprise
//
// if module's assets path as Admin module:
// moduleName/views/assets/javascripts(stylesheets)
// you need set subModuleName as admin
// gulp --worker--admin
//
// if you need run task for subModule in modules
// example: worker module inline_edit subModule:
// gulp --worker--inline_edit
//
// gulp --media--media_library--true
//
// -----------------------------------------------------------------------------

function moduleTasks(moduleNames) {
  var moduleName = moduleNames.name;
  var subModuleName = moduleNames.subName;
  var useSubName = moduleNames.useSubName;

  var pathto = function(file) {
    if (moduleName && subModuleName) {
      if (subModuleName == 'admin') {
        return '../' + moduleName + '/views/assets/' + file;
      } else if (subModuleName == 'enterprise') {
        return '../../../enterprise.getqor.com/' + moduleName + '/views/themes/' + moduleName + '/assets/' + file;
      } else if (useSubName) {
        return '../' + moduleName + '/' + subModuleName + '/views/themes/' + subModuleName + '/assets/' + file;
      } else {
        return '../' + moduleName + '/' + subModuleName + '/views/themes/' + moduleName + '/assets/' + file;
      }
    }
    return '../' + moduleName + '/views/themes/' + moduleName + '/assets/' + file;
  };

  var scripts = {
    src: pathto('javascripts/'),
    watch: pathto('javascripts/**/*.js')
  };
  var styles = {
    src: pathto('stylesheets/'),
    watch: pathto('stylesheets/**/*.scss')
  };

  function getFolders(dir) {
    return fs.readdirSync(dir).filter(function(file) {
      return fs.statSync(path.join(dir, file)).isDirectory();
    });
  }

  gulp.task('js', function() {
    var scriptPath = scripts.src;
    var folders = getFolders(scriptPath);
    var task = folders.map(function(folder) {
      return gulp
        .src(path.join(scriptPath, folder, '/*.js'))
        .pipe(
          eslint({
            configFile: '.eslintrc'
          })
        )
        .pipe(
          babel({
            presets: ['es2015']
          })
        )
        .pipe(eslint.format())
        .pipe(plugins.concat(folder + '.js'))
        .pipe(
          plugins.uglify({
            drop_debugger: false
          })
        )
        .pipe(gulp.dest(scriptPath));
    });

    return es.concat.apply(null, task);
  });

  gulp.task('css', function() {
    var stylePath = styles.src;
    var folders = getFolders(stylePath);
    var task = folders.map(function(folder) {
      return gulp
        .src(path.join(stylePath, folder, '/*.scss'))
        .pipe(
          plugins.sass({
            outputStyle: 'compressed'
          })
        )
        .pipe(plugins.minifyCss())
        .pipe(rename(folder + '.css'))
        .pipe(gulp.dest(stylePath));
    });

    return es.concat.apply(null, task);
  });

  gulp.task('watch', function() {
    gulp.watch(scripts.watch, ['js']);
    gulp.watch(styles.watch, ['css']);
  });

  gulp.task('default', ['watch']);
  gulp.task('release', ['js', 'css']);
}

// Init
// -----------------------------------------------------------------------------

if (moduleName.name) {
  var taskPath = moduleName.name + '/views/themes/' + moduleName.name + '/assets/';
  var runModuleName = 'Running "' + moduleName.name + '" module task in "' + taskPath + '"...';

  if (moduleName.subName) {
    if (moduleName.subName == 'admin') {
      taskPath = moduleName.name + '/views/assets/';
      runModuleName = 'Running "' + moduleName.name + '" module task in "' + taskPath + '"...';
    } else if (moduleName.subName == 'enterprise') {
      taskPath = '../../../enterprise.getqor.com/' + moduleName.name + '/views/themes/' + moduleName.name + '/assets/';
      runModuleName = 'Running "' + moduleName.name + '" module task in "' + taskPath + '"...';
    } else if (moduleName.useSubName) {
      taskPath = moduleName.name + '/' + moduleName.subName + '/views/themes/' + moduleName.subName + '/assets/';
      runModuleName = 'Running "' + moduleName.name + ' > ' + moduleName.subName + '" module task in "' + taskPath + '"...';
    } else {
      taskPath = moduleName.name + '/' + moduleName.subName + '/views/themes/' + moduleName.name + '/assets/';
      runModuleName = 'Running "' + moduleName.name + ' > ' + moduleName.subName + '" module task in "' + taskPath + '"...';
    }
  }
  console.log(runModuleName);
  moduleTasks(moduleName);
} else {
  console.log('Running "admin" module task in "admin/views/assets/"...');
  adminTasks();
}

// Task for compress js and css vendor assets
gulp.task('combineJavaScriptVendor', function() {
  return gulp
    .src(['!../admin/views/assets/javascripts/vendors/jquery.min.js', '../admin/views/assets/javascripts/vendors/*.js'])
    .pipe(plugins.concat('vendors.js'))
    .pipe(gulp.dest('../admin/views/assets/javascripts'));
});

gulp.task('compressCSSVendor', function() {
  return gulp
    .src('../admin/views/assets/stylesheets/vendors/*.css')
    .pipe(plugins.concat('vendors.css'))
    .pipe(gulp.dest('../admin/views/assets/stylesheets'));
});
<commit_msg>adjsut assets file name<commit_after>'use strict';

var gulp = require('gulp');
var babel = require('gulp-babel');
var eslint = require('gulp-eslint');
var plugins = require('gulp-load-plugins')();

var fs = require('fs');
var path = require('path');
var es = require('event-stream');
var rename = require('gulp-rename');

var moduleName = (function() {
  var args = process.argv;
  var length = args.length;
  var i = 0;
  var name;
  var subName;
  var useSubName;

  while (i++ < length) {
    if (/^--+(\w+)/i.test(args[i])) {
      name = args[i].split('--')[1];
      subName = args[i].split('--')[2];
      useSubName = args[i].split('--')[3];
      break;
    }
  }
  return {
    name: name,
    subName: subName,
    useSubName: useSubName
  };
})();

// Admin Module
// Command: gulp [task]
// Admin is default task
// Watch Admin module: gulp
// -----------------------------------------------------------------------------

function adminTasks() {
  var pathto = function(file) {
    return '../admin/views/assets/' + file;
  };
  var scripts = {
    src: pathto('javascripts/app/*.js'),
    dest: pathto('javascripts'),
    qor: pathto('javascripts/qor/*.js'),
    qorInit: pathto('javascripts/qor/qor-config.js'),
    qorCommon: pathto('javascripts/qor/qor-common.js'),
    qorAdmin: [pathto('javascripts/qor.js'), pathto('javascripts/app.js')],
    all: ['gulpfile.js', pathto('javascripts/qor/*.js')]
  };
  var styles = {
    src: pathto('stylesheets/scss/{app,qor}.scss'),
    dest: pathto('stylesheets'),
    vendors: pathto('stylesheets/vendors'),
    main: pathto('stylesheets/{qor,app}.css'),
    qorAdmin: [pathto('stylesheets/vendors.css'), pathto('stylesheets/qor.css'), pathto('stylesheets/app.css')],
    scss: pathto('stylesheets/scss/**/*.scss')
  };

  gulp.task('qor', function() {
    return gulp
      .src([scripts.qorInit, scripts.qorCommon, scripts.qor])
      .pipe(plugins.concat('qor.js'))
      .pipe(plugins.uglify())
      .pipe(gulp.dest(scripts.dest));
  });

  gulp.task('js', ['qor'], function() {
    return gulp
      .src(scripts.src)
      .pipe(
        eslint({
          configFile: '.eslintrc'
        })
      )
      .pipe(plugins.concat('app.js'))
      .pipe(plugins.uglify())
      .pipe(gulp.dest(scripts.dest));
  });

  gulp.task('qor+', function() {
    return gulp
      .src([scripts.qorInit, scripts.qorCommon, scripts.qor])
      .pipe(
        eslint({
          configFile: '.eslintrc'
        })
      )
      .pipe(
        babel({
          presets: ['es2015']
        })
      )
      .pipe(eslint.format())
      .pipe(plugins.concat('qor.js'))
      .pipe(plugins.uglify())
      .pipe(gulp.dest(scripts.dest));
  });

  gulp.task('js+', function() {
    return gulp
      .src(scripts.src)
      .pipe(
        babel({
          presets: ['es2015']
        })
      )
      .pipe(eslint.format())
      .pipe(plugins.concat('app.js'))
      .pipe(plugins.uglify())
      .pipe(gulp.dest(scripts.dest));
  });

  gulp.task('sass', function() {
    return gulp.src(styles.src).pipe(plugins.sass()).pipe(gulp.dest(styles.dest));
  });

  gulp.task('css', ['sass'], function() {
    return gulp
      .src(styles.main)
      .pipe(plugins.autoprefixer())
      .pipe(plugins.csscomb())
      .pipe(plugins.minifyCss())
      .pipe(gulp.dest(styles.dest));
  });

  gulp.task('release_js', function() {
    return gulp.src(scripts.qorAdmin).pipe(plugins.concat('qor_admin_default.js')).pipe(gulp.dest(scripts.dest));
  });

  gulp.task('release_css', function() {
    return gulp.src(styles.qorAdmin).pipe(plugins.concat('qor_admin_default.css')).pipe(gulp.dest(styles.dest));
  });

  gulp.task('release', ['qor+', 'js+', 'css', 'release_js', 'release_css']);

  var watcher = gulp.task('watch', function() {
    var watch_qor = gulp.watch(scripts.qor, ['qor+']);
    var watch_js = gulp.watch(scripts.src, ['js+']);
    var watch_css = gulp.watch(styles.scss, ['css']);

    gulp.watch(styles.qorAdmin, ['release_css']);
    gulp.watch(scripts.qorAdmin, ['release_js']);

    watch_qor.on('change', function(event) {
      console.log(':==> File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
    watch_js.on('change', function(event) {
      console.log(':==> File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
    watch_css.on('change', function(event) {
      console.log(':==> File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
  });

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

// -----------------------------------------------------------------------------
// Other Modules
// Command: gulp [task] --moduleName--subModuleName
//
//  example:
// Watch Worker module: gulp --worker
//
// if module's assets just as normal path:
// moduleName/views/themes/moduleName/assets/javascripts(stylesheets)
// just use gulp --worker
//
// if module's assets in enterprise as normal path:
// moduleName/views/themes/moduleName/assets/javascripts(stylesheets)
// just use gulp --microsite--enterprise
//
// if module's assets path as Admin module:
// moduleName/views/assets/javascripts(stylesheets)
// you need set subModuleName as admin
// gulp --worker--admin
//
// if you need run task for subModule in modules
// example: worker module inline_edit subModule:
// gulp --worker--inline_edit
//
// gulp --media--media_library--true
//
// -----------------------------------------------------------------------------

function moduleTasks(moduleNames) {
  var moduleName = moduleNames.name;
  var subModuleName = moduleNames.subName;
  var useSubName = moduleNames.useSubName;

  var pathto = function(file) {
    if (moduleName && subModuleName) {
      if (subModuleName == 'admin') {
        return '../' + moduleName + '/views/assets/' + file;
      } else if (subModuleName == 'enterprise') {
        return '../../../enterprise.getqor.com/' + moduleName + '/views/themes/' + moduleName + '/assets/' + file;
      } else if (useSubName) {
        return '../' + moduleName + '/' + subModuleName + '/views/themes/' + subModuleName + '/assets/' + file;
      } else {
        return '../' + moduleName + '/' + subModuleName + '/views/themes/' + moduleName + '/assets/' + file;
      }
    }
    return '../' + moduleName + '/views/themes/' + moduleName + '/assets/' + file;
  };

  var scripts = {
    src: pathto('javascripts/'),
    watch: pathto('javascripts/**/*.js')
  };
  var styles = {
    src: pathto('stylesheets/'),
    watch: pathto('stylesheets/**/*.scss')
  };

  function getFolders(dir) {
    return fs.readdirSync(dir).filter(function(file) {
      return fs.statSync(path.join(dir, file)).isDirectory();
    });
  }

  gulp.task('js', function() {
    var scriptPath = scripts.src;
    var folders = getFolders(scriptPath);
    var task = folders.map(function(folder) {
      return gulp
        .src(path.join(scriptPath, folder, '/*.js'))
        .pipe(
          eslint({
            configFile: '.eslintrc'
          })
        )
        .pipe(
          babel({
            presets: ['es2015']
          })
        )
        .pipe(eslint.format())
        .pipe(plugins.concat(folder + '.js'))
        .pipe(
          plugins.uglify({
            drop_debugger: false
          })
        )
        .pipe(gulp.dest(scriptPath));
    });

    return es.concat.apply(null, task);
  });

  gulp.task('css', function() {
    var stylePath = styles.src;
    var folders = getFolders(stylePath);
    var task = folders.map(function(folder) {
      return gulp
        .src(path.join(stylePath, folder, '/*.scss'))
        .pipe(
          plugins.sass({
            outputStyle: 'compressed'
          })
        )
        .pipe(plugins.minifyCss())
        .pipe(rename(folder + '.css'))
        .pipe(gulp.dest(stylePath));
    });

    return es.concat.apply(null, task);
  });

  gulp.task('watch', function() {
    gulp.watch(scripts.watch, ['js']);
    gulp.watch(styles.watch, ['css']);
  });

  gulp.task('default', ['watch']);
  gulp.task('release', ['js', 'css']);
}

// Init
// -----------------------------------------------------------------------------

if (moduleName.name) {
  var taskPath = moduleName.name + '/views/themes/' + moduleName.name + '/assets/';
  var runModuleName = 'Running "' + moduleName.name + '" module task in "' + taskPath + '"...';

  if (moduleName.subName) {
    if (moduleName.subName == 'admin') {
      taskPath = moduleName.name + '/views/assets/';
      runModuleName = 'Running "' + moduleName.name + '" module task in "' + taskPath + '"...';
    } else if (moduleName.subName == 'enterprise') {
      taskPath = '../../../enterprise.getqor.com/' + moduleName.name + '/views/themes/' + moduleName.name + '/assets/';
      runModuleName = 'Running "' + moduleName.name + '" module task in "' + taskPath + '"...';
    } else if (moduleName.useSubName) {
      taskPath = moduleName.name + '/' + moduleName.subName + '/views/themes/' + moduleName.subName + '/assets/';
      runModuleName = 'Running "' + moduleName.name + ' > ' + moduleName.subName + '" module task in "' + taskPath + '"...';
    } else {
      taskPath = moduleName.name + '/' + moduleName.subName + '/views/themes/' + moduleName.name + '/assets/';
      runModuleName = 'Running "' + moduleName.name + ' > ' + moduleName.subName + '" module task in "' + taskPath + '"...';
    }
  }
  console.log(runModuleName);
  moduleTasks(moduleName);
} else {
  console.log('Running "admin" module task in "admin/views/assets/"...');
  adminTasks();
}

// Task for compress js and css vendor assets
gulp.task('combineJavaScriptVendor', function() {
  return gulp
    .src(['!../admin/views/assets/javascripts/vendors/jquery.min.js', '../admin/views/assets/javascripts/vendors/*.js'])
    .pipe(plugins.concat('vendors.js'))
    .pipe(gulp.dest('../admin/views/assets/javascripts'));
});

gulp.task('compressCSSVendor', function() {
  return gulp
    .src('../admin/views/assets/stylesheets/vendors/*.css')
    .pipe(plugins.concat('vendors.css'))
    .pipe(gulp.dest('../admin/views/assets/stylesheets'));
});
<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');
var path = require('path');

var Saws = function(AWS) {
  this.AWS = AWS;
  this.stage = 'development';

  this.DEBUG = function() {
    if(process.env.SAWS_DEBUG) {
      console.log.apply(console, arguments);
    }
  };

  var self = this;

  // Load all files from ./services
  fs.readdirSync(path.join(__dirname, "services")).forEach(function(file) {
    require('./services/' + file)(self);
  });

  return this;
};

module.exports = {
  Saws: Saws,
  AWSStub: require('../tests/aws-stub')
};
<commit_msg>More restrictive module loader<commit_after>'use strict';
var fs = require('fs');
var path = require('path');

var Saws = function(AWS) {
  this.AWS = AWS;
  this.stage = 'development';

  this.DEBUG = function() {
    if(process.env.SAWS_DEBUG) {
      console.log.apply(console, arguments);
    }
  };

  var self = this;

  // Load all files from ./services
  var files = fs.readdirSync(path.join(__dirname, "services"));
  files = files.filter(function(filename) {
    return path.extname(filename) === '.js';
  }, files);

  files.forEach(function(file) {
    require('./services/' + file)(self);
  });

  return this;
};

module.exports = {
  Saws: Saws,
  AWSStub: require('../tests/aws-stub')
};
<|endoftext|>


<commit_before>var _ = require('lodash');
var buildConfig = require('./scripts/build/config');
var fs = require('fs');
var gulp = require('gulp');
var karma = require('karma').server;
var path = require('path');
var VinylFile = require('vinyl');
var argv = require('yargs').argv;
var cached = require('gulp-cached');
var concat = require('gulp-concat');
var del = require('del');
var gulpif = require('gulp-if');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var through2 = require('through2');
var runSequence = require('run-sequence');
var watch = require('gulp-watch');
var exec = require('child_process').exec;
var babel = require('gulp-babel');
var traceur = require('gulp-traceur');
var webpack = require('gulp-webpack');
var tsc = require('gulp-typescript');
var lazypipe = require('lazypipe');
var cache = require('gulp-cached');
var connect = require('gulp-connect');

gulp.task('clean.build', function() {
  runSequence(
    'clean',
    'transpile',
    //'bundle.deps',
    'bundle.js',
    'examples',
    'sass',
    'fonts',
    'vendor');
})

gulp.task('build', function() {
  runSequence(
    'transpile',
    'bundle.js',
    'examples',
    'sass',
    'fonts',
    'vendor');
})

gulp.task('watch', function() {

  runSequence(
    'transpile',
    'bundle.js',
    'examples',
    'sass',
    'fonts',
    'vendor',
    'serve',

    function() {
      watch(['ionic/**/*.js', 'ionic/**/*.ts', '!ionic/components/*/test/**/*'], function() {
        runSequence(
          'transpile',
          'bundle.js',
          'examples'
        )
      });

      watch('ionic/components/*/test/**/*', function() {
        gulp.start('examples');
      });

      watch('ionic/**/*.scss', function() {
        gulp.start('sass');
      });
    })
});

gulp.task('serve', function() {
  connect.server({
    port: 8000,
    livereload: false
  });
});

gulp.task('clean', function(done) {
  del(['dist/'], done);
});

var traceurOptions = {
  annotations: true,
  types: true,
  outputLanguage: 'es6'
};

var babelOptions = {
  optional: ['es7.decorators'],
  /*plugins: [
    './transformers/disable-define',
    'angular2-annotations',
    'type-assertion:after'
  ],*/
  modules: "system",
  moduleIds: true,
  getModuleId: function(name) {
    return "ionic/" + name;
  }
};

var exampleBabelOptions = {
  optional: ['es7.decorators'],
  /*plugins: [
    './transformers/disable-define',
    'angular2-annotations',
    'type-assertion:after'
  ],*/
  modules: "system",
  moduleIds: true,
  getModuleId: function(name) {
    return "dist/examples/" + name.split('/test').join('');
  }
};

var tscOptions = {
  target: 'ES6',
  // Don't use the version of typescript that gulp-typescript depends on, we need 1.5
  // see https://github.com/ivogabe/gulp-typescript#typescript-version
  typescript: require('typescript'),
  allowNonTsExtensions: true,
  isolatedModules: true,
  //declaration: true, //generate d.ts files
  emitDecoratorMetadata: true,
  experimentalDecorators: true,
  noEmitOnError: false,  // ignore errors
  rootDir: '.'
}

gulp.task('transpile', function() {
  var stream = gulp.src(['ionic/**/*.ts', 'ionic/**/*.js', '!ionic/components/*/test/**/*', '!ionic/init.js'])
             .pipe(cache('transpile', { optimizeMemory: true }))
             .pipe(tsc(tscOptions, null, tsc.reporter.nullReporter()))
            // .on('error', function(error) {
            //   stream.emit('error', error);
            // })
            // .pipe(traceur(traceurOptions))
            // .on('error', function (err) {
            //   console.log("ERROR: " + err.message);
            //   this.emit('end');
            // })
             .pipe(gulp.dest('dist/js/es6/ionic'))
             .pipe(babel(babelOptions))
             .on('error', function (err) {
               console.log("ERROR: " + err.message);
               this.emit('end');
             })
             .pipe(gulp.dest('dist/js/es5/ionic'))

  return stream;
});

gulp.task('bundle.js', function() {
  return gulp.src(['dist/js/es5/ionic/**/*.js', 'ionic/init.js'])
             .pipe(concat('ionic.bundle.js'))
             .pipe(gulp.dest('dist/js/'));
});

//gulp.task('bundle.deps', function() {
//  var Builder = require('systemjs-builder')
//  var builder = new Builder();
//  return builder.loadConfig('config.js').then(function(){
//    // add ionic and angular2 build paths, since config.js is loaded at runtime from
//    // tests we don't want to put them there
//    builder.config({
//      baseURL: 'file:' + process.cwd(),
//      paths : {
//        "ionic/*": "dist/js/es6/ionic/*.js"
//      }
//    });
//    return builder.build('dist/js/es6/ionic/**/* - [dist/js/es6/ionic/**/*]', 'dist/js/dependencies.js');
//  }, function(error){
//    console.log("Error building dependency bundle, have you transpiled Ionic and/or built Angular2 yet?");
//    throw new Error(error);
//  })
//});

gulp.task('examples', function() {
  var buildTest = lazypipe()
             //.pipe(traceur, traceurOptions)
             .pipe(tsc, tscOptions, null, tsc.reporter.nullReporter())
             .pipe(babel, exampleBabelOptions)

  // Get each test folder with gulp.src
  return gulp.src('ionic/components/*/test/*/**/*')
    .pipe(cache('examples', { optimizeMemory: true }))
    .pipe(gulpif(/.ts$/, buildTest()))
    .on('error', function (err) {
            console.log("ERROR: " + err.message);
            this.emit('end');
        })
    .pipe(gulpif(/index.js$/, createIndexHTML())) //TSC changes .ts to .js
    .pipe(rename(function(file) {
      file.dirname = file.dirname.replace(path.sep + 'test' + path.sep, path.sep)
    }))
    .pipe(gulp.dest('dist/examples/'))

  function createIndexHTML() {
    var template = _.template(
      fs.readFileSync('scripts/e2e/ionic.template.html')
    )({
      buildConfig: buildConfig
    });

    return through2.obj(function(file, enc, next) {
      var self = this;

      var module = path.dirname(file.path)
                      .replace(__dirname, '')
                      .replace('/ionic/components/', 'dist/examples/')
                      .replace('/test/', '/') +
                      '/index';

      var indexContents = template.replace('{{MODULE}}', module);

      self.push(new VinylFile({
        base: file.base,
        contents: new Buffer(indexContents),
        path: path.join(path.dirname(file.path), 'index.html'),
      }));
      next(null, file);
    });
  }
});

gulp.task('sass', function() {
  return gulp.src('ionic/ionic.scss')
    .pipe(sass({
      onError: function(err) {
        console.log(err)
      }
    }))
    .pipe(autoprefixer(buildConfig.autoprefixer))
    .pipe(gulp.dest('dist/css/'));
});

gulp.task('fonts', function() {
  return gulp.src('ionic/components/icon/fonts/**/*')
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('vendor', function() {
  return gulp.src(['scripts/vendor/**/*'])
    .pipe(gulp.dest('dist/vendor'));
});

require('./scripts/snapshot/snapshot.task')(gulp, argv, buildConfig);

gulp.task('karma', function() {
  return karma.start({ configFile: __dirname + '/scripts/test/karma.conf.js' })
});

gulp.task('karma-watch', function() {
  return karma.start({ configFile: __dirname + '/scripts/test/karma-watch.conf.js' })
});

gulp.task('e2e', ['sass'], function() {
  var indexContents = _.template( fs.readFileSync('scripts/e2e/index.template.html') )({
    buildConfig: buildConfig
  });
  var testTemplate = _.template( fs.readFileSync('scripts/e2e/e2e.template.js') )

  var platforms = [
    'android',
    'core',
    'ios',
  ];

  gulp.src(['ionic/**/*.js'])
           .pipe(gulp.dest('dist/src'));

  // Get each test folder with gulp.src
  return gulp.src(buildConfig.src.e2e)
    .pipe(cached('e2e'))
    .pipe(rename(function(file) {
      file.dirname = file.dirname.replace(path.sep + 'test' + path.sep, path.sep)
    }))
    .pipe(gulpif(/main.js$/, processMain()))
    //.pipe(gulpif(/e2e.js$/, createPlatformTests()))
    .pipe(gulp.dest(buildConfig.dist + '/e2e'));

    function processMain() {
      return through2.obj(function(file, enc, next) {
        var self = this;
        self.push(new VinylFile({
          base: file.base,
          contents: new Buffer(indexContents),
          path: path.join(path.dirname(file.path), 'index.html'),
        }));
        next(null, file);
      })
    }

    function createPlatformTests(file) {
      return through2.obj(function(file, enc, next) {
        var self = this
        var relativePath = path.dirname(file.path.replace(/^.*?ionic(\/|\\)components(\/|\\)/, ''))
        var contents = file.contents.toString()
        platforms.forEach(function(platform) {
          var platformContents = testTemplate({
            contents: contents,
            buildConfig: buildConfig,
            relativePath: relativePath,
            platform: platform
          })
          self.push(new VinylFile({
            base: file.base,
            contents: new Buffer(platformContents),
            path: file.path.replace(/e2e.js$/, platform + '.e2e.js')
          }))
        })
        next()
      })
    }

});
<commit_msg>typescript build syntax errors<commit_after>var _ = require('lodash');
var buildConfig = require('./scripts/build/config');
var fs = require('fs');
var gulp = require('gulp');
var karma = require('karma').server;
var path = require('path');
var VinylFile = require('vinyl');
var argv = require('yargs').argv;
var cached = require('gulp-cached');
var concat = require('gulp-concat');
var del = require('del');
var gulpif = require('gulp-if');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var through2 = require('through2');
var runSequence = require('run-sequence');
var watch = require('gulp-watch');
var exec = require('child_process').exec;
var babel = require('gulp-babel');
var traceur = require('gulp-traceur');
var webpack = require('gulp-webpack');
var tsc = require('gulp-typescript');
var lazypipe = require('lazypipe');
var cache = require('gulp-cached');
var connect = require('gulp-connect');

gulp.task('clean.build', function() {
  runSequence(
    'clean',
    'transpile',
    //'bundle.deps',
    'bundle.js',
    'examples',
    'sass',
    'fonts',
    'vendor');
})

gulp.task('build', function() {
  runSequence(
    'transpile',
    'bundle.js',
    'examples',
    'sass',
    'fonts',
    'vendor');
})

gulp.task('watch', function() {

  runSequence(
    'transpile',
    'bundle.js',
    'examples',
    'sass',
    'fonts',
    'vendor',
    'serve',

    function() {
      watch(['ionic/**/*.js', 'ionic/**/*.ts', '!ionic/components/*/test/**/*'], function() {
        runSequence(
          'transpile',
          'bundle.js',
          'examples'
        )
      });

      watch('ionic/components/*/test/**/*', function() {
        gulp.start('examples');
      });

      watch('ionic/**/*.scss', function() {
        gulp.start('sass');
      });
    })
});

gulp.task('serve', function() {
  connect.server({
    port: 8000,
    livereload: false
  });
});

gulp.task('clean', function(done) {
  del(['dist/'], done);
});

var traceurOptions = {
  annotations: true,
  types: true,
  outputLanguage: 'es6'
};

var babelOptions = {
  optional: ['es7.decorators'],
  /*plugins: [
    './transformers/disable-define',
    'angular2-annotations',
    'type-assertion:after'
  ],*/
  modules: "system",
  moduleIds: true,
  getModuleId: function(name) {
    return "ionic/" + name;
  }
};

var exampleBabelOptions = {
  optional: ['es7.decorators'],
  /*plugins: [
    './transformers/disable-define',
    'angular2-annotations',
    'type-assertion:after'
  ],*/
  modules: "system",
  moduleIds: true,
  getModuleId: function(name) {
    return "dist/examples/" + name.split('/test').join('');
  }
};

var tscOptions = {
  target: 'ES6',
  // Don't use the version of typescript that gulp-typescript depends on, we need 1.5
  // see https://github.com/ivogabe/gulp-typescript#typescript-version
  typescript: require('typescript'),
  allowNonTsExtensions: true,
  isolatedModules: true,
  //declaration: true, //generate d.ts files
  emitDecoratorMetadata: true,
  experimentalDecorators: true,
  noEmitOnError: false,  // ignore errors
  rootDir: '.'
}
var tscReporter = {
    error: function (error) {
        console.error(error.message);
    }
};

gulp.task('transpile', function() {
  var stream = gulp.src(['ionic/**/*.ts', 'ionic/**/*.js', '!ionic/components/*/test/**/*', '!ionic/init.js'])
                   .pipe(cache('transpile', { optimizeMemory: true }))
                   .pipe(tsc(tscOptions, null, tscReporter))
                // .on('error', function(error) {
                //   stream.emit('error', error);
                // })
                // .pipe(traceur(traceurOptions))
                // .on('error', function (err) {
                //   console.log("ERROR: " + err.message);
                //   this.emit('end');
                // })
                   .pipe(gulp.dest('dist/js/es6/ionic'))
                   .pipe(babel(babelOptions))
                   .on('error', function (err) {
                     console.log("ERROR: " + err.message);
                     this.emit('end');
                   })
                   .pipe(gulp.dest('dist/js/es5/ionic'))

  return stream;
});

gulp.task('bundle.js', function() {
  return gulp.src(['dist/js/es5/ionic/**/*.js', 'ionic/init.js'])
             .pipe(concat('ionic.bundle.js'))
             .pipe(gulp.dest('dist/js/'));
});

//gulp.task('bundle.deps', function() {
//  var Builder = require('systemjs-builder')
//  var builder = new Builder();
//  return builder.loadConfig('config.js').then(function(){
//    // add ionic and angular2 build paths, since config.js is loaded at runtime from
//    // tests we don't want to put them there
//    builder.config({
//      baseURL: 'file:' + process.cwd(),
//      paths : {
//        "ionic/*": "dist/js/es6/ionic/*.js"
//      }
//    });
//    return builder.build('dist/js/es6/ionic/**/* - [dist/js/es6/ionic/**/*]', 'dist/js/dependencies.js');
//  }, function(error){
//    console.log("Error building dependency bundle, have you transpiled Ionic and/or built Angular2 yet?");
//    throw new Error(error);
//  })
//});

gulp.task('examples', function() {
  var buildTest = lazypipe()
             //.pipe(traceur, traceurOptions)
             .pipe(tsc, tscOptions, null, tsc.reporter.nullReporter())
             .pipe(babel, exampleBabelOptions)

  // Get each test folder with gulp.src
  return gulp.src('ionic/components/*/test/*/**/*')
    .pipe(cache('examples', { optimizeMemory: true }))
    .pipe(gulpif(/.ts$/, buildTest()))
    .on('error', function (err) {
            console.log("ERROR: " + err.message);
            this.emit('end');
        })
    .pipe(gulpif(/index.js$/, createIndexHTML())) //TSC changes .ts to .js
    .pipe(rename(function(file) {
      file.dirname = file.dirname.replace(path.sep + 'test' + path.sep, path.sep)
    }))
    .pipe(gulp.dest('dist/examples/'))

  function createIndexHTML() {
    var template = _.template(
      fs.readFileSync('scripts/e2e/ionic.template.html')
    )({
      buildConfig: buildConfig
    });

    return through2.obj(function(file, enc, next) {
      var self = this;

      var module = path.dirname(file.path)
                      .replace(__dirname, '')
                      .replace('/ionic/components/', 'dist/examples/')
                      .replace('/test/', '/') +
                      '/index';

      var indexContents = template.replace('{{MODULE}}', module);

      self.push(new VinylFile({
        base: file.base,
        contents: new Buffer(indexContents),
        path: path.join(path.dirname(file.path), 'index.html'),
      }));
      next(null, file);
    });
  }
});

gulp.task('sass', function() {
  return gulp.src('ionic/ionic.scss')
    .pipe(sass({
      onError: function(err) {
        console.log(err)
      }
    }))
    .pipe(autoprefixer(buildConfig.autoprefixer))
    .pipe(gulp.dest('dist/css/'));
});

gulp.task('fonts', function() {
  return gulp.src('ionic/components/icon/fonts/**/*')
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('vendor', function() {
  return gulp.src(['scripts/vendor/**/*'])
    .pipe(gulp.dest('dist/vendor'));
});

require('./scripts/snapshot/snapshot.task')(gulp, argv, buildConfig);

gulp.task('karma', function() {
  return karma.start({ configFile: __dirname + '/scripts/test/karma.conf.js' })
});

gulp.task('karma-watch', function() {
  return karma.start({ configFile: __dirname + '/scripts/test/karma-watch.conf.js' })
});

gulp.task('e2e', ['sass'], function() {
  var indexContents = _.template( fs.readFileSync('scripts/e2e/index.template.html') )({
    buildConfig: buildConfig
  });
  var testTemplate = _.template( fs.readFileSync('scripts/e2e/e2e.template.js') )

  var platforms = [
    'android',
    'core',
    'ios',
  ];

  gulp.src(['ionic/**/*.js'])
           .pipe(gulp.dest('dist/src'));

  // Get each test folder with gulp.src
  return gulp.src(buildConfig.src.e2e)
    .pipe(cached('e2e'))
    .pipe(rename(function(file) {
      file.dirname = file.dirname.replace(path.sep + 'test' + path.sep, path.sep)
    }))
    .pipe(gulpif(/main.js$/, processMain()))
    //.pipe(gulpif(/e2e.js$/, createPlatformTests()))
    .pipe(gulp.dest(buildConfig.dist + '/e2e'));

    function processMain() {
      return through2.obj(function(file, enc, next) {
        var self = this;
        self.push(new VinylFile({
          base: file.base,
          contents: new Buffer(indexContents),
          path: path.join(path.dirname(file.path), 'index.html'),
        }));
        next(null, file);
      })
    }

    function createPlatformTests(file) {
      return through2.obj(function(file, enc, next) {
        var self = this
        var relativePath = path.dirname(file.path.replace(/^.*?ionic(\/|\\)components(\/|\\)/, ''))
        var contents = file.contents.toString()
        platforms.forEach(function(platform) {
          var platformContents = testTemplate({
            contents: contents,
            buildConfig: buildConfig,
            relativePath: relativePath,
            platform: platform
          })
          self.push(new VinylFile({
            base: file.base,
            contents: new Buffer(platformContents),
            path: file.path.replace(/e2e.js$/, platform + '.e2e.js')
          }))
        })
        next()
      })
    }

});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var runSequence = require('run-sequence');
var preprocess = require('gulp-preprocess');
var clean = require('gulp-clean');
var $ = require('gulp-load-plugins')();
var robots = require('gulp-robots');
var minifyHTML = require('gulp-htmlmin');
var jshintStylish = require('jshint-stylish');
var less = require('gulp-less');
var coffeelint = require('gulp-coffeelint');
var imagemin = require('gulp-imagemin');
var sitemap = require('gulp-sitemap');
var mainBowerFiles = require('main-bower-files');
var modernizr = require('gulp-modernizr');
var pngquant = require('imagemin-pngquant');
var browserSync = require('browser-sync').create();
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var watchify = require('watchify');
var browserify = require('browserify');
var coffeeify = require('coffeeify');
var hbsfy = require('hbsfy');
var gutil = require('gulp-util');
var assign = require('lodash.assign');
var coffee = require('gulp-coffee');
var rev = require('gulp-rev');
var revReplace = require("gulp-rev-replace");
var gzip = require('gulp-gzip');
var git = require('git-rev');
var fs = require('fs');
var replace = require('gulp-replace');
var srizer = require('gulp-srizer');
var through = require('through2');
var log = gutil.log;
var colors = gutil.colors;
var nano = require('gulp-cssnano');
var uglify = require('gulp-uglify');

const siteUrl = 'https://sritest.io';

var gzip_options = {
    threshold: '1kb',
    gzipOptions: {
        level: 9
    }
};

/*
 * Define paths
 */
const paths = {
      jsFiles: 'js/src/*.coffee',
      jsDirectory: 'js/',
      jsVendorFiles: 'js/vendor/*.js',
      jsVendorDirectory: 'js/vendor',
      cssFiles: 'css/*.css',
      cssDirectory: 'css/',
      cssVendorFiles: 'css/vendor/*.css',
      cssVendorDirectory: 'css/vendor',
      lessFiles: 'less/*.less',
      lessDirectory: 'less/',
      imageFiles: 'img/**/*',
      imageDirectory: 'img/',
      textFiles: '*.txt',
      htmlFiles: '*.html',
      tiles: '*.png',
      faviconDir: 'favicon/'
};

const SRC = './src/';
const DST = './dist/';

/*
 * Delete the dist directory
 */
gulp.task('clean', function() {
    return gulp.src(DST)
        .pipe(clean());
});

/*
 * Write Git commit longhash into file
 */
gulp.task('git-longhash', function () {
    var file = DST + '/build.txt';
    return git.long(function (longhash) {
      fs.writeFile(file, longhash)
    })
});

/*
 * Delete the dist directory
 */
gulp.task('gzip', function() {
    var assets = [DST + '**/*.js', DST + '**/*.css', DST + '**/*.html'];
    return gulp.src(assets)
        .pipe(gzip(gzip_options))
        .pipe(gulp.dest(DST));
});

/*
 * Remove original files after versioning
 */
var rmOrig = function() {
  return through.obj(function(file, enc, cb) {

    if (file.revOrigPath) {
      log(colors.red('DELETING'), file.revOrigPath);
      fs.unlink(file.revOrigPath, function(err) {
        // TODO: emit an error if err
      });
    }

    this.push(file); // Pass file when you're done
    return cb() // notify through2 you're done
  });
};

gulp.task('revision', function() {
    var assets = [
      DST + '**/*.js',
      DST + '**/*.css',
      DST + paths.imageFiles
    ];
    return gulp.src(assets, {base: DST})
        .pipe(rev())
        .pipe(gulp.dest(DST))
        .pipe(rmOrig())
        .pipe(rev.manifest({
          base: DST,
          merge: true,
          path: DST + 'rev-manifest.json'
        }))
        .pipe(gulp.dest(DST));
});

gulp.task('revreplace', ['revision'], function(){
  var manifest = gulp.src(DST + '/rev-manifest.json');
  return gulp.src(DST + paths.htmlFiles)
    .pipe(revReplace({manifest: manifest}))
    .pipe(gulp.dest(DST));
});

/*
 * Copy favicons
 */
gulp.task('copy-favicon', function() {
    return gulp.src(SRC + paths.faviconDir + '*')
        .pipe(gulp.dest(DST));
});

/*
 * Generate robots.txt
 */
gulp.task('robots', function () {
    return gulp.src(SRC+'index.html')
        .pipe(robots({
            sitemap: siteUrl + '/sitemap.xml'
        }))
        .pipe(gulp.dest(DST));
});

/*
 * Process HTML files
 */
gulp.task('html-dist', function() {
  return gulp.src(SRC+paths.htmlFiles)
      .pipe(gulp.dest(DST));
});

/*
 * Add code snippets into HTML files from templates
 */
gulp.task('inject-code-snippets', function () {
  var options = {
    includeBase: SRC + 'templates/'
  };
  return gulp.src(DST+paths.htmlFiles)
      .pipe(preprocess(options))
      .pipe(gulp.dest(DST));
});

/*
 * Minify HTML files
 */
// We keep this separate from 'html-dist', otherwise 'generate-sri' won't work
gulp.task('minify-html', function () {
  var opts = {
      collapseWhitespace: true
  };
  return gulp.src(DST+paths.htmlFiles)
      .pipe($.removeHtmlComments())
      .pipe(minifyHTML(opts))
      .pipe(gulp.dest(DST));
});

/*
 * Optimize images
 */
gulp.task('minimize-images', function() {
    return gulp.src(SRC+paths.imageFiles)
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest(DST+paths.imageDirectory));
});

/*
 * Copy vendor js files
 */
gulp.task('copy-vendor-js', function() {
    return gulp.src(SRC+paths.jsVendorFiles)
        .pipe(gulp.dest(DST+paths.jsVendorDirectory));
});

/*
 * Copy vendor CSS files
 */
gulp.task('copy-vendor-css', function() {
    return gulp.src(SRC+paths.cssVendorFiles)
        .pipe(gulp.dest(DST+paths.cssVendorDirectory));
});

/*
 * Copy fonts for Semantic UI icons
 */
gulp.task('copy-semantic-ui-icons', function() {
    return gulp.src(SRC+paths.cssVendorDirectory+'/themes/default/assets/fonts/*')
        .pipe(gulp.dest(DST+paths.cssVendorDirectory+'/themes/default/assets/fonts/'));
});

gulp.task('install-bower-packages-js', function() {
    return gulp.src(mainBowerFiles({
          filter: /\..*js$/i,
          overrides: {
            "jquery": {
              "main": "**/jquery.min.js"
            },
            "highlightjs": {
              "main": "**/highlight.pack.min.js"
            }
          }
        }))
        .pipe(gulp.dest(DST+paths.jsVendorDirectory));
});

gulp.task('install-bower-packages-css', function() {
  return gulp.src(mainBowerFiles({
        filter: /\..*css$/i,
          overrides: {
            "highlightjs": {
              "main": "**/androidstudio.css"
            }
          }
        }))
        .pipe(gulp.dest(DST+paths.cssVendorDirectory));
});

/*
 * Compile LESS to CSS
 */
gulp.task('less-dist', function () {
    return gulp.src(SRC+paths.lessDirectory+'app.less')
        .pipe(less())
        .pipe($.autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe(nano())
        .pipe(gulp.dest(DST+paths.cssDirectory))
        .pipe(browserSync.stream());
});

/*
 * Lint your JavaScript
 */
gulp.task('coffee-lint', function () {
    return gulp.src(SRC+paths.jsFiles)
        .pipe(coffeelint())
        .pipe(coffeelint.reporter());
});

/*
 * Lint your CSS
 */
gulp.task('css-lint', function () {
    return gulp.src(SRC+paths.cssFiles)
        .pipe($.csslint())
        .pipe($.csslint.reporter());
});

/*
 * Beautify your CSS
 */
gulp.task('beautify-css', function () {
    return gulp.src(SRC+paths.cssFiles)
        .pipe($.cssbeautify())
        .pipe(gulp.dest(SRC+paths.cssDirectory));
});

/*
 * Strip, prefix, minify and concatenate your CSS during a deployment
 */
gulp.task('css-dist', function () {
    return gulp.src(SRC+paths.cssFiles)
        .pipe($.plumber())
        .pipe($.autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe($.concat('main.css'), {newLine: ''})
        .pipe(nano())
        .pipe(gulp.dest(DST+paths.cssDirectory))
});

/*
 * Watchify CoffeeScript files into main.js
 */
gulp.task('coffee-watch', bundle);

var customOpts = {
  entries: [
      SRC+paths.jsDirectory+'/app/bundle.coffee'
  ],
  debug: true,
  transform: [coffeeify, [hbsfy, {extensions: ['hbs']}]]
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));

b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal

function bundle() {
  gutil.log('Compiling scripts ...');
  return b.bundle()
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
        .pipe($.concat('app.js'))
        .pipe(uglify())
        .on('error', gutil.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DST+paths.jsDirectory))
    .pipe(browserSync.stream());
}

/*
 * Browserify CoffeeScript files into main.js
 */
gulp.task('browserify-dist', function () {
  var opts = {
    entries: [
        SRC+paths.jsDirectory+'/app/bundle.coffee'
    ],
    debug: true,
    transform: [coffeeify, [hbsfy, {extensions: ['hbs']}]],
    cache: {},
    packageCache: {}
  };

  var b = browserify(opts);
  return b.bundle()
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
        .pipe($.concat('app.js'))
        .pipe(uglify())
        .on('error', gutil.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DST+paths.jsDirectory));
});

/*
 * Compile your Coffeescript
 */
gulp.task('coffee-dist', function () {
    return gulp.src(SRC+paths.jsFiles)
        .pipe(coffeelint())
        .pipe(coffee({bare: true}).on('error', gutil.log))
        .pipe(coffeelint.reporter())
        .pipe(gulp.dest(DST+paths.jsDirectory));
});

/*
 * Strip, minify and concatenate your JavaScript during a deployment
 */
gulp.task('generate-modernizr', function () {
    return gulp.src(DST+paths.jsDirectory+'*.js')
        .pipe(modernizr())
        .pipe($.uglify())
        .pipe(gulp.dest(DST+paths.jsDirectory));
});

/*
 * Generate sitemap file
 */
gulp.task('sitemap', function () {
    var files = [SRC+'**/*.html', '!'+SRC+'50x.html'];
    gulp.src(files)
        .pipe(sitemap({
            siteUrl: siteUrl
        }))
        .pipe(replace('.html', ''))
        .pipe(gulp.dest(DST));
});

/*
 * Generate SRI hashes for all local assets
 */
gulp.task('generate-sri', function() {
    var files = [
      DST + paths.htmlFiles,
    ];
    var options = {
      fileExt: ['css', 'js']
    }
    return gulp.src(files)
        .pipe(srizer())
        .pipe(gulp.dest(DST));
});

/*
 * Watchers
 */
gulp.task('watch', function () {
    gulp.watch(SRC+paths.jsFiles, ['coffee-lint']);
    gulp.watch(SRC+paths.cssFiles, ['css-lint']);
    gulp.watch(SRC+paths.lessDirectory+'app.less', ['less-dist']);
});

/*
 * Build project for production
 */
gulp.task('build', function(callback) {
  runSequence('clean',
              'robots',
              ['minimize-images', 'copy-favicon'],
              'coffee-lint',
              ['css-dist', 'browserify-dist', 'coffee-dist', 'html-dist', 'less-dist'],
              ['copy-vendor-js', 'copy-vendor-css', 'copy-semantic-ui-icons'],
              ['install-bower-packages-js', 'install-bower-packages-css'],
              'generate-modernizr',
              'sitemap',
              'inject-code-snippets',
              'revreplace',
              'generate-sri',
              'minify-html',
              'gzip',
              'git-longhash',
              callback
  )
});

/*
 * Build project for developing
 */
gulp.task('develop', function(callback) {
  runSequence('clean',
              ['minimize-images', 'copy-favicon'],
              'coffee-lint',
              ['css-dist', 'browserify-dist', 'coffee-dist', 'html-dist', 'less-dist'],
              ['copy-vendor-js', 'copy-vendor-css', 'copy-semantic-ui-icons'],
              ['install-bower-packages-js', 'install-bower-packages-css'],
              'generate-modernizr',
              'inject-code-snippets',
              callback
  )
});

gulp.task('beautify', ['beautify-css']);

/*
 * Serve files trough BrowserSync
 */
gulp.task('html-watch', ['html-dist', 'inject-code-snippets'], browserSync.reload);
gulp.task('js-watch', ['coffee-dist'], browserSync.reload);
gulp.task('less-watch', ['less-dist']);

gulp.task('serve', ['coffee-watch'], function () {
    browserSync.init({
        server: {
          baseDir: DST
        }
    });
    gulp.watch(SRC+paths.htmlFiles, ['html-watch']);
    gulp.watch(SRC+paths.lessFiles, ['less-watch']);
    gulp.watch(SRC+paths.jsFiles, ['js-watch']);
});
<commit_msg>Fix robots file<commit_after>'use strict';

var gulp = require('gulp');
var runSequence = require('run-sequence');
var preprocess = require('gulp-preprocess');
var clean = require('gulp-clean');
var $ = require('gulp-load-plugins')();
var robots = require('gulp-robots');
var minifyHTML = require('gulp-htmlmin');
var jshintStylish = require('jshint-stylish');
var less = require('gulp-less');
var coffeelint = require('gulp-coffeelint');
var imagemin = require('gulp-imagemin');
var sitemap = require('gulp-sitemap');
var mainBowerFiles = require('main-bower-files');
var modernizr = require('gulp-modernizr');
var pngquant = require('imagemin-pngquant');
var browserSync = require('browser-sync').create();
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var watchify = require('watchify');
var browserify = require('browserify');
var coffeeify = require('coffeeify');
var hbsfy = require('hbsfy');
var gutil = require('gulp-util');
var assign = require('lodash.assign');
var coffee = require('gulp-coffee');
var rev = require('gulp-rev');
var revReplace = require("gulp-rev-replace");
var gzip = require('gulp-gzip');
var git = require('git-rev');
var fs = require('fs');
var replace = require('gulp-replace');
var srizer = require('gulp-srizer');
var through = require('through2');
var log = gutil.log;
var colors = gutil.colors;
var nano = require('gulp-cssnano');
var uglify = require('gulp-uglify');

const siteUrl = 'https://sritest.io';

var gzip_options = {
    threshold: '1kb',
    gzipOptions: {
        level: 9
    }
};

/*
 * Define paths
 */
const paths = {
      jsFiles: 'js/src/*.coffee',
      jsDirectory: 'js/',
      jsVendorFiles: 'js/vendor/*.js',
      jsVendorDirectory: 'js/vendor',
      cssFiles: 'css/*.css',
      cssDirectory: 'css/',
      cssVendorFiles: 'css/vendor/*.css',
      cssVendorDirectory: 'css/vendor',
      lessFiles: 'less/*.less',
      lessDirectory: 'less/',
      imageFiles: 'img/**/*',
      imageDirectory: 'img/',
      textFiles: '*.txt',
      htmlFiles: '*.html',
      tiles: '*.png',
      faviconDir: 'favicon/'
};

const SRC = './src/';
const DST = './dist/';

/*
 * Delete the dist directory
 */
gulp.task('clean', function() {
    return gulp.src(DST)
        .pipe(clean());
});

/*
 * Write Git commit longhash into file
 */
gulp.task('git-longhash', function () {
    var file = DST + '/build.txt';
    return git.long(function (longhash) {
      fs.writeFile(file, longhash)
    })
});

/*
 * Delete the dist directory
 */
gulp.task('gzip', function() {
    var assets = [DST + '**/*.js', DST + '**/*.css', DST + '**/*.html'];
    return gulp.src(assets)
        .pipe(gzip(gzip_options))
        .pipe(gulp.dest(DST));
});

/*
 * Remove original files after versioning
 */
var rmOrig = function() {
  return through.obj(function(file, enc, cb) {

    if (file.revOrigPath) {
      log(colors.red('DELETING'), file.revOrigPath);
      fs.unlink(file.revOrigPath, function(err) {
        // TODO: emit an error if err
      });
    }

    this.push(file); // Pass file when you're done
    return cb() // notify through2 you're done
  });
};

gulp.task('revision', function() {
    var assets = [
      DST + '**/*.js',
      DST + '**/*.css',
      DST + paths.imageFiles
    ];
    return gulp.src(assets, {base: DST})
        .pipe(rev())
        .pipe(gulp.dest(DST))
        .pipe(rmOrig())
        .pipe(rev.manifest({
          base: DST,
          merge: true,
          path: DST + 'rev-manifest.json'
        }))
        .pipe(gulp.dest(DST));
});

gulp.task('revreplace', ['revision'], function(){
  var manifest = gulp.src(DST + '/rev-manifest.json');
  return gulp.src(DST + paths.htmlFiles)
    .pipe(revReplace({manifest: manifest}))
    .pipe(gulp.dest(DST));
});

/*
 * Copy favicons
 */
gulp.task('copy-favicon', function() {
    return gulp.src(SRC + paths.faviconDir + '*')
        .pipe(gulp.dest(DST));
});

/*
 * Generate robots.txt
 */
gulp.task('robots', function () {
    return gulp.src(SRC+'index.html')
        .pipe(robots({
            sitemap: siteUrl + '/sitemap.xml',
            disallow: []
        }))
        .pipe(gulp.dest(DST));
});

/*
 * Process HTML files
 */
gulp.task('html-dist', function() {
  return gulp.src(SRC+paths.htmlFiles)
      .pipe(gulp.dest(DST));
});

/*
 * Add code snippets into HTML files from templates
 */
gulp.task('inject-code-snippets', function () {
  var options = {
    includeBase: SRC + 'templates/'
  };
  return gulp.src(DST+paths.htmlFiles)
      .pipe(preprocess(options))
      .pipe(gulp.dest(DST));
});

/*
 * Minify HTML files
 */
// We keep this separate from 'html-dist', otherwise 'generate-sri' won't work
gulp.task('minify-html', function () {
  var opts = {
      collapseWhitespace: true
  };
  return gulp.src(DST+paths.htmlFiles)
      .pipe($.removeHtmlComments())
      .pipe(minifyHTML(opts))
      .pipe(gulp.dest(DST));
});

/*
 * Optimize images
 */
gulp.task('minimize-images', function() {
    return gulp.src(SRC+paths.imageFiles)
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest(DST+paths.imageDirectory));
});

/*
 * Copy vendor js files
 */
gulp.task('copy-vendor-js', function() {
    return gulp.src(SRC+paths.jsVendorFiles)
        .pipe(gulp.dest(DST+paths.jsVendorDirectory));
});

/*
 * Copy vendor CSS files
 */
gulp.task('copy-vendor-css', function() {
    return gulp.src(SRC+paths.cssVendorFiles)
        .pipe(gulp.dest(DST+paths.cssVendorDirectory));
});

/*
 * Copy fonts for Semantic UI icons
 */
gulp.task('copy-semantic-ui-icons', function() {
    return gulp.src(SRC+paths.cssVendorDirectory+'/themes/default/assets/fonts/*')
        .pipe(gulp.dest(DST+paths.cssVendorDirectory+'/themes/default/assets/fonts/'));
});

gulp.task('install-bower-packages-js', function() {
    return gulp.src(mainBowerFiles({
          filter: /\..*js$/i,
          overrides: {
            "jquery": {
              "main": "**/jquery.min.js"
            },
            "highlightjs": {
              "main": "**/highlight.pack.min.js"
            }
          }
        }))
        .pipe(gulp.dest(DST+paths.jsVendorDirectory));
});

gulp.task('install-bower-packages-css', function() {
  return gulp.src(mainBowerFiles({
        filter: /\..*css$/i,
          overrides: {
            "highlightjs": {
              "main": "**/androidstudio.css"
            }
          }
        }))
        .pipe(gulp.dest(DST+paths.cssVendorDirectory));
});

/*
 * Compile LESS to CSS
 */
gulp.task('less-dist', function () {
    return gulp.src(SRC+paths.lessDirectory+'app.less')
        .pipe(less())
        .pipe($.autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe(nano())
        .pipe(gulp.dest(DST+paths.cssDirectory))
        .pipe(browserSync.stream());
});

/*
 * Lint your JavaScript
 */
gulp.task('coffee-lint', function () {
    return gulp.src(SRC+paths.jsFiles)
        .pipe(coffeelint())
        .pipe(coffeelint.reporter());
});

/*
 * Lint your CSS
 */
gulp.task('css-lint', function () {
    return gulp.src(SRC+paths.cssFiles)
        .pipe($.csslint())
        .pipe($.csslint.reporter());
});

/*
 * Beautify your CSS
 */
gulp.task('beautify-css', function () {
    return gulp.src(SRC+paths.cssFiles)
        .pipe($.cssbeautify())
        .pipe(gulp.dest(SRC+paths.cssDirectory));
});

/*
 * Strip, prefix, minify and concatenate your CSS during a deployment
 */
gulp.task('css-dist', function () {
    return gulp.src(SRC+paths.cssFiles)
        .pipe($.plumber())
        .pipe($.autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe($.concat('main.css'), {newLine: ''})
        .pipe(nano())
        .pipe(gulp.dest(DST+paths.cssDirectory))
});

/*
 * Watchify CoffeeScript files into main.js
 */
gulp.task('coffee-watch', bundle);

var customOpts = {
  entries: [
      SRC+paths.jsDirectory+'/app/bundle.coffee'
  ],
  debug: true,
  transform: [coffeeify, [hbsfy, {extensions: ['hbs']}]]
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));

b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal

function bundle() {
  gutil.log('Compiling scripts ...');
  return b.bundle()
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
        .pipe($.concat('app.js'))
        .pipe(uglify())
        .on('error', gutil.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DST+paths.jsDirectory))
    .pipe(browserSync.stream());
}

/*
 * Browserify CoffeeScript files into main.js
 */
gulp.task('browserify-dist', function () {
  var opts = {
    entries: [
        SRC+paths.jsDirectory+'/app/bundle.coffee'
    ],
    debug: true,
    transform: [coffeeify, [hbsfy, {extensions: ['hbs']}]],
    cache: {},
    packageCache: {}
  };

  var b = browserify(opts);
  return b.bundle()
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
        .pipe($.concat('app.js'))
        .pipe(uglify())
        .on('error', gutil.log)
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DST+paths.jsDirectory));
});

/*
 * Compile your Coffeescript
 */
gulp.task('coffee-dist', function () {
    return gulp.src(SRC+paths.jsFiles)
        .pipe(coffeelint())
        .pipe(coffee({bare: true}).on('error', gutil.log))
        .pipe(coffeelint.reporter())
        .pipe(gulp.dest(DST+paths.jsDirectory));
});

/*
 * Strip, minify and concatenate your JavaScript during a deployment
 */
gulp.task('generate-modernizr', function () {
    return gulp.src(DST+paths.jsDirectory+'*.js')
        .pipe(modernizr())
        .pipe($.uglify())
        .pipe(gulp.dest(DST+paths.jsDirectory));
});

/*
 * Generate sitemap file
 */
gulp.task('sitemap', function () {
    var files = [SRC+'**/*.html', '!'+SRC+'50x.html'];
    gulp.src(files)
        .pipe(sitemap({
            siteUrl: siteUrl
        }))
        .pipe(replace('.html', ''))
        .pipe(gulp.dest(DST));
});

/*
 * Generate SRI hashes for all local assets
 */
gulp.task('generate-sri', function() {
    var files = [
      DST + paths.htmlFiles,
    ];
    var options = {
      fileExt: ['css', 'js']
    }
    return gulp.src(files)
        .pipe(srizer())
        .pipe(gulp.dest(DST));
});

/*
 * Watchers
 */
gulp.task('watch', function () {
    gulp.watch(SRC+paths.jsFiles, ['coffee-lint']);
    gulp.watch(SRC+paths.cssFiles, ['css-lint']);
    gulp.watch(SRC+paths.lessDirectory+'app.less', ['less-dist']);
});

/*
 * Build project for production
 */
gulp.task('build', function(callback) {
  runSequence('clean',
              'robots',
              ['minimize-images', 'copy-favicon'],
              'coffee-lint',
              ['css-dist', 'browserify-dist', 'coffee-dist', 'html-dist', 'less-dist'],
              ['copy-vendor-js', 'copy-vendor-css', 'copy-semantic-ui-icons'],
              ['install-bower-packages-js', 'install-bower-packages-css'],
              'generate-modernizr',
              'sitemap',
              'inject-code-snippets',
              'revreplace',
              'generate-sri',
              'minify-html',
              'gzip',
              'git-longhash',
              callback
  )
});

/*
 * Build project for developing
 */
gulp.task('develop', function(callback) {
  runSequence('clean',
              ['minimize-images', 'copy-favicon'],
              'coffee-lint',
              ['css-dist', 'browserify-dist', 'coffee-dist', 'html-dist', 'less-dist'],
              ['copy-vendor-js', 'copy-vendor-css', 'copy-semantic-ui-icons'],
              ['install-bower-packages-js', 'install-bower-packages-css'],
              'generate-modernizr',
              'inject-code-snippets',
              callback
  )
});

gulp.task('beautify', ['beautify-css']);

/*
 * Serve files trough BrowserSync
 */
gulp.task('html-watch', ['html-dist', 'inject-code-snippets'], browserSync.reload);
gulp.task('js-watch', ['coffee-dist'], browserSync.reload);
gulp.task('less-watch', ['less-dist']);

gulp.task('serve', ['coffee-watch'], function () {
    browserSync.init({
        server: {
          baseDir: DST
        }
    });
    gulp.watch(SRC+paths.htmlFiles, ['html-watch']);
    gulp.watch(SRC+paths.lessFiles, ['less-watch']);
    gulp.watch(SRC+paths.jsFiles, ['js-watch']);
});
<|endoftext|>


<commit_before>$(document).ready(function(){

    var plants = [];
    function plant(){
        this.px = Math.floor(Math.random() * 890) + 10;
        this.py = Math.floor(Math.random() * 490) + 10;
        this.el = $('<div>').addClass('plant').appendTo('body').css('top', this.py + 'px').css('left', this.px + 'px').css('display', 'block');
    }

    var snakes = [];
    function snake(){
        this.dr = 'right';
        this.snkblks = [];

        var skblk = new snkblk();
        skblk.el.removeClass('box').addClass('head');
        this.snkblks.push(skblk);
    }

    function snkblk(){
        this.el = $('<div>').addClass('box').appendTo('body').css('display', 'block');
        this.xx = parseInt(this.el.css('left').match(/\d*/)[0]);
        this.yy = parseInt(this.el.css('top').match(/\d*/)[0]);
        this.oxx = 0;
        this.oyy = 0;
    }

    function init(){
        var pt;

        //make a new snake
        var ske = new snake();

        //add the snake to list of snakes
        snakes.push(ske);

        for (i = 0; i < 10; i++) {
            pt = new plant();
            plants.push(pt);
        }
    }

    function scoreboard() {
      $('<div>').addClass('scorebd').appendTo('body').text("use arrow keys to control your snake! eat red plants.");
      $('.scorebd').live('mouseover', function(){
        $(this).css('height', '33px');
      }).live('mouseout', function(){
        $(this).css('height', '30px');
      }).fadeOut(15000);
    }

    init();
    scoreboard();

    var arrow = {
        'left': 37,
        'right': 39,
        'up': 38,
        'down': 40
    };

    function movesnake(snke, dr){
        var snkblks = snke.snkblks;
        var moved = false;

        for (k = 0; k < snkblks.length; k++) {
            var snk = snkblks[k];
            var el = snk.el;
            var xx = snk.xx;
            var yy = snk.yy;

            if (k == 0) {
                if (dr == 'left' && xx - 10 > 0 && snke.dr !== 'right' || snakes.length != 1) {
                    xx = xx - 10;
                    moved = true;
                    snke.dr = 'left';
                }
                if (dr == 'right' && xx + 10 < 900 && snke.dr !== 'left' || snakes.length != 1) {
                    xx = xx + 10;
                    moved = true;
                    snke.dr = 'right';
                }
                if (dr == 'up' && yy - 10 > 0 && snke.dr !== 'down' || snakes.length != 1) {
                    yy = yy - 10;
                    snke.dr = 'up';
                    moved = true;
                }
                if (dr == 'down' && yy + 10 < 600 && snke.dr !== 'up' || snakes.length != 1) {
                    yy = yy + 10;
                    moved = true;
                    snke.dr = 'down';
                }

                if (moved == false)
                    return;

                el.css('left', xx + "px");
                el.css('top', yy + "px");
                snk.oxx = snk.xx;
                snk.oyy = snk.yy;
                snk.xx = xx;
                snk.yy = yy;

                //plants.forEach(function(pt){
                for (i = 0; i < plants.length; i++) {
                  var pt = plants[i];
                  var xd = Math.abs(pt.px - xx);
                  var yd = Math.abs(pt.py - yy);
                  if (xd < 10 && yd < 10) {
                      $(pt.el).remove();
                      plants.splice(i, 1);
                      var skblk = new snkblk();
                      skblk.xx = snkblks[snkblks.length - 1].oxx;
                      skblk.yy = snkblks[snkblks.length - 1].oyy;
                      snkblks.push(skblk);
//                        pt = new plant();
//                        plants.push(pt);
                    }
                };
            } else {
              var snk = snkblks[k];
              var snk1 = snkblks[k - 1];
              var el = snk.el;
              snk.oxx = snk.xx;
              snk.oyy = snk.yy;
              snk.xx = snk1.oxx;
              snk.yy = snk1.oyy;

              el.css('top', snk.yy + "px");
              el.css('left', snk.xx + "px");
            }
        }
    }

  //attach timer to keep moving.
  setInterval(function(){
    var snke = snakes[0];
    movesnake(snke, snke.dr);
  }, 500);

  $('body').bind('keydown', function(ev){
      var key = ev.keyCode || ev.which;

      //moving only the first snake.
      var snke = snakes[0], dr = '';

      if (key == arrow.left)  dr = 'left';
      if (key == arrow.right) dr = 'right';
      if (key == arrow.up)    dr = 'up';
      if (key == arrow.down)  dr = 'down';

      movesnake(snke, dr);
  });
});
<commit_msg>added scoreboard, type of plants, snake dies.<commit_after>$(document).ready(function(){

    var plants = [];
    function plant(){
        this.type = Math.floor(Math.random() * 3);
        this.px = Math.floor(Math.random() * 890) + 10;
        this.py = Math.floor(Math.random() * 490) + 10;

        this.el = $('<div>').addClass('plant').appendTo('body').css('top', this.py + 'px').css('left', this.px + 'px').css('display', 'block');
        if (this.type == 0){
            //eat reds; and you die.
            this.el.css('background', 'red');
        }
        if (this.type == 1){
            //eat blue; +5 pts.
            this.el.css('background', 'blue');
        }
        if (this.type == 2){
            //eat yellow +10 pts.
            this.el.css('background', 'yellow');
        }

    }

    var snakes = [];
    function snake(){
        this.score = 0;
        this.dr = 'right';
        this.snkblks = [];

        var skblk = new snkblk();
        skblk.el.removeClass('box').addClass('head');
        this.snkblks.push(skblk);
    }

    function snkblk(){
        this.el = $('<div>').addClass('box').appendTo('body').css('display', 'block');
        this.xx = parseInt(this.el.css('left').match(/\d*/)[0]);
        this.yy = parseInt(this.el.css('top').match(/\d*/)[0]);
        this.oxx = 0;
        this.oyy = 0;
    }

    function init(){
        var pt;

        //make a new snake
        var ske = new snake();

        //add the snake to list of snakes
        snakes.push(ske);

        for (i = 0; i < 10; i++) {
            pt = new plant();
            plants.push(pt);
        }
    }

    function scoreboard() {
      $('<div>').addClass('scorebd').appendTo('body').text("use arrow keys to control your snake! eat red plants.").fadeOut(3000);
      $('.scorebd').live('mouseover', function(){
        $(this).css('height', '33px');
      }).live('mouseout', function(){
        $(this).css('height', '30px');
      });
    }

    init();
    scoreboard();

    var arrow = {
        'left': 37,
        'right': 39,
        'up': 38,
        'down': 40
    };

    function movesnake(snke, dr){
        var snkblks = snke.snkblks;
        var moved = false;

        for (k = 0; k < snkblks.length; k++) {
            var snk = snkblks[k];
            var el = snk.el;
            var xx = snk.xx;
            var yy = snk.yy;

            if (k == 0) {
                if (dr == 'left' && xx - 10 > 0 && snke.dr !== 'right' || snakes.length != 1) {
                    xx = xx - 10;
                    moved = true;
                    snke.dr = 'left';
                }
                if (dr == 'right' && xx + 10 < 900 && snke.dr !== 'left' || snakes.length != 1) {
                    xx = xx + 10;
                    moved = true;
                    snke.dr = 'right';
                }
                if (dr == 'up' && yy - 10 > 0 && snke.dr !== 'down' || snakes.length != 1) {
                    yy = yy - 10;
                    snke.dr = 'up';
                    moved = true;
                }
                if (dr == 'down' && yy + 10 < 600 && snke.dr !== 'up' || snakes.length != 1) {
                    yy = yy + 10;
                    moved = true;
                    snke.dr = 'down';
                }

                if (moved == false)
                    return;

                el.css('left', xx + "px");
                el.css('top', yy + "px");
                snk.oxx = snk.xx;
                snk.oyy = snk.yy;
                snk.xx = xx;
                snk.yy = yy;

                //plants.forEach(function(pt){
                for (i = 0; i < plants.length; i++) {
                  var pt = plants[i];
                  var xd = Math.abs(pt.px - xx);
                  var yd = Math.abs(pt.py - yy);
                  if (xd < 10 && yd < 10) {
                      $(pt.el).remove();

                      ptyp = pt.type;

                      if (ptyp == 1)
                        snke.score = snke.score + 5;

                      if (ptyp == 2)
                        snke.score = snke.score + 10;

                      if (ptyp == 0) {
                        //you die.
                        var blk = 0;
                        for(i=0; i<snkblks.length; i++){
                          blk = snkblks[i];
                          $(blk.el).fadeOut();
                        };
                        snakes.splice(0, 1);
                        $('.scorebd').text('game over! you are dead : ' + snke.score + ', refresh to play again.').fadeIn();
                        return;
                      }

                      plants.splice(i, 1);
                      $('.scorebd').text('your score : ' + snke.score).fadeIn();

                      for (i=0; i<ptyp; i++) {
                        var skblk = new snkblk();
                        skblk.xx = snkblks[snkblks.length - 1].oxx;
                        skblk.yy = snkblks[snkblks.length - 1].oyy;
                        snkblks.push(skblk);
                        pt = new plant();
                        plants.push(pt);
                      }
                    }
                };
            } else {
              var snk = snkblks[k];
              var snk1 = snkblks[k - 1];
              var el = snk.el;
              snk.oxx = snk.xx;
              snk.oyy = snk.yy;
              snk.xx = snk1.oxx;
              snk.yy = snk1.oyy;

              el.css('top', snk.yy + "px");
              el.css('left', snk.xx + "px");
            }
        }
    }

  //attach timer to keep moving.
  setInterval(function(){
    var snke = snakes[0];
    movesnake(snke, snke.dr);
  }, 500);

  $('body').bind('keydown', function(ev){
      var key = ev.keyCode || ev.which;

      //moving only the first snake.
      var snke = snakes[0], dr = '';

      if (key == arrow.left)  dr = 'left';
      if (key == arrow.right) dr = 'right';
      if (key == arrow.up)    dr = 'up';
      if (key == arrow.down)  dr = 'down';

      movesnake(snke, dr);
  });
});
<|endoftext|>


<commit_before><commit_msg>update<commit_after><|endoftext|>


<commit_before>'use strict'

const Server = require('karma').Server

const getConfig = require('./browser-config')
const utils = require('../utils')

function karma (config) {
  return new Promise((resolve, reject) => {
    const server = new Server(config, (exitCode) => {
      if (exitCode > 0) {
        reject(new Error('Some tests are failing'))
      }

      resolve()
    })

    server.start()
  })
}

function testBrowser (isWebworker) {
  const postHook = utils.hook('browser', 'post')
  const preHook = utils.hook('browser', 'pre')

  return (ctx) => {
    return preHook(ctx)
      .then(() => getConfig(isWebworker, ctx))
      .then(karma)
      .then(() => postHook(ctx))
  }
}

module.exports = {
  default: testBrowser(false),
  webworker: testBrowser(true)
}
<commit_msg>fix: windows takes 2 minutes to exit<commit_after>'use strict'

const Server = require('karma').Server

const getConfig = require('./browser-config')
const utils = require('../utils')

function karma (config) {
  return new Promise((resolve, reject) => {
    const server = new Server(config)

    server.once('exit', force => force(resolve))

    server.start()
  })
}

function testBrowser (isWebworker) {
  const postHook = utils.hook('browser', 'post')
  const preHook = utils.hook('browser', 'pre')

  return (ctx) => {
    return preHook(ctx)
      .then(() => getConfig(isWebworker, ctx))
      .then(karma)
      .then(() => postHook(ctx))
  }
}

module.exports = {
  default: testBrowser(false),
  webworker: testBrowser(true)
}
<|endoftext|>