'use strict';

var gulp = require('gulp');

var browserSync = require('browser-sync');
var httpProxy = require('http-proxy');

/* This configuration allow you to configure browser sync to proxy your backend */
var proxyTarget = 'http://server/context/'; // The location of your backend
var proxyApiPrefix = 'api'; // The element in the URL which differentiate between API request and static file request

var proxy = httpProxy.createProxyServer({
  target: proxyTarget
});

function proxyMiddleware(req, res, next) {
  if (req.url.indexOf(proxyApiPrefix) !== -1) {
    proxy.web(req, res);
  } else {
    next();
  }
}

function browserSyncInit(baseDir, files, browser) {
  browser = browser === undefined ? 'default' : browser;

  browserSync.instance = browserSync.init(files, {
    startPath: '/index.html',
    server: {
      baseDir: baseDir,
      middleware: proxyMiddleware
    },
    browser: browser
  });

}

gulp.task('serve', ['watch'], function () {
  browserSyncInit([
    'app',
    '.tmp'
  ], [
    'app/*.html',
    '.tmp/styles/**/*.css',
    'app/scripts/**/*.js',
    'app/partials/**/*.html',
    'app/images/**/*'
  ]);
});

gulp.task('serve:dist', ['build'], function () {
  browserSyncInit('dist');
});

gulp.task('serve:e2e', function () {
  browserSyncInit(['app', '.tmp'], null, []);
});

gulp.task('serve:e2e-dist', ['watch'], function () {
  browserSyncInit('dist', null, []);
});

@@ -279,16 +279,17 @@
 backend%0A
+%0A
 var prox
@@ -293,323 +293,379 @@
 roxy
-ApiPrefix = 'api'; // The element in the URL which differentiate between API request and static file request%0A%0Avar proxy = httpProxy.createProxyS
+ = httpProxy.createProxyServer(%7B%0A  target: proxyTarget%0A%7D);%0A%0A/* proxyMiddleware forwards static files to BrowserSync s
 erver
-(%7B
 %0A  
-target: proxyTarget%0A%7D);%0A%0Afunction proxyMiddleware(req, res, next) %7B%0A  if (req.url.indexOf(proxyApiPrefix) !== -1) %7B%0A    proxy.web(req, res);%0A  %7D else %7B%0A    next(
+ and forwards dynamic requests to your real backend */%0Afunction proxyMiddleware(req, res, next) %7B%0A  if (/%5C.(html%7Cpng%7Ccss%7Cjpg%7Cjpeg%7Cgif%7Cjs%7Cico%7Cxml%7Crss%7Ctxt)(%5C?(r%7Cv%7Crel%7Crev)=%5B%5C-%5C.%5Cw%5D*)?$/.test(req.url)) %7B%0A    next();%0A  %7D else %7B%0A    proxy.web(req, res
 );%0A 

Improve middleware with a better static file filter.