/*=============================================================================

Define ZeroPush Service Provider

=============================================================================
178944
function ZeroPush(keys){
  if (!keys) return
  this.name = "zeropush"
  this.keys = keys

  this.initialize = function() {
    this.client = new zeroPush(this.keys.server_token);
  }

  this.send = function(data, callback) {
    var context = this;
    var zeropushStat;
	var deviceType = getZeroPushDeviceType(data.deviceType);
	var notification = getNotificationObject(deviceType, data.message);

	context.client.register([data.deviceToken], function(err, response) {

		if (err) {
			zeropushStat = new ZeroPushErrorStatus(err);
			debug("-_-_ FAILED with zeropush _-_-");
            debug(zeropushStat);
            return callback(zeropushStat);
		}

		context.client.notify(deviceType, [data.deviceToken], notification, function (err, result) {

	        if (err) {
	          zeropushStat = new ZeroPushErrorStatus(err);
	          debug("-_-_ FAILED with zeropush _-_-");
	          debug(zeropushStat);
	          return callback(zeropushStat);
	        }
	        else {
	          zeropushStat = new ZeroPushSuccessStatus(result);
	          debug("-_-_ sent with zeropush _-_-");
	          result.service = context;
	          result.status = zeropushStat;
	          debug(result);
	          return callback(null, result);
	        }
		});
    });
  }

  debug("zeropush initing")
  this.initialize()
}
986441
function PushWrapper() {
    // Autobahn|JS connection object for push API (utilizes the WAMP protocol)
    this._connection = new autobahn.Connection({
        "url": POLONIEX_PUSH_URL,
        "realm": POLONIEX_PUSH_REALM
    });

    // Internally-routed callback sets for connection management events
    this._cxnCallbacksOpen = new Array();
    this._cxnCallbacksClose = new Array();

    // Internal lookup table for linking subscriptions to callbacks
    this._subLinks = {};
    this._subLinksId = 0;

    // Number of currently active subscriptions
    this._activeSubs = 0;

    // Handle connection open event
    this._connection.onopen = (session) => {
        // Loop through all open callbacks
        for (let i = 0; i < this._cxnCallbacksOpen.length; i++) {
            this._cxnCallbacksOpen[i](session);
        }
    };

    // Handle connection close event
    this._connection.onclose = (reason, details) => {
        // Loop through all close callbacks
        for (let i = 0; i < this._cxnCallbacksClose.length; i++) {
            this._cxnCallbacksClose[i](reason, details);
        }
    };
}
119331
function serve(name, options, init) {
    var _pkg = pkg();
    if (chek_1.isPlainObject(name)) {
        init = options;
        options = name;
        name = undefined;
    }
    if (chek_1.isBoolean(options)) {
        init = options;
        options = undefined;
    }
    var defaults = {
        server: {
            baseDir: './dist'
        }
    };
    name = name || 'dev-server';
    options = chek_1.extend({}, defaults, options);
    var bsync = chek_1.tryRootRequire('browser-sync');
    if (!bsync)
        logger_1.log.error('browser-sync not found try >> npm install browser-sync -s');
    var server = bsync.create(name);
    if (init !== false)
        server.init(options, function (err) {
            if (err) {
                logger_1.log.error(err);
            }
            else {
                logger_1.log.notify("browser Sync server " + name + " started.");
            }
        });
    return server;
}
794341
function createGlobalManagerService($http, authService) {
  //Init the sync service
  syncNetworkInit.initSync($http).catch(function(error) {
    logger.getLogger().error("Failed to initialize sync", error);
  });
  var syncManager = new SyncManager();
  authService.setLoginListener(function(profileData) {
    syncManager.syncManagerMap(profileData);
  });

  authService.setLogoutListener(function() {
    syncManager.removeManagers();
  });
  return syncManager;
}
1210574
async function start() {
  if (server) return server;
  server = express();
  server.use(errorOverlayMiddleware());
  server.use(express.static(path.resolve(__dirname, '../public')));

  // Configure client-side hot module replacement
  const clientConfig = webpackConfig.find(config => config.name === 'client');
  clientConfig.entry.client = ['./tools/lib/webpackHotDevClient']
    .concat(clientConfig.entry.client)
    .sort((a, b) => b.includes('polyfill') - a.includes('polyfill'));
  clientConfig.output.filename = clientConfig.output.filename.replace(
    'chunkhash',
    'hash',
  );
  clientConfig.output.chunkFilename = clientConfig.output.chunkFilename.replace(
    'chunkhash',
    'hash',
  );
  clientConfig.module.rules = clientConfig.module.rules.filter(
    x => x.loader !== 'null-loader',
  );
  clientConfig.plugins.push(new webpack.HotModuleReplacementPlugin());

  // Configure server-side hot module replacement
  const serverConfig = webpackConfig.find(config => config.name === 'server');
  serverConfig.output.hotUpdateMainFilename = 'updates/[hash].hot-update.json';
  serverConfig.output.hotUpdateChunkFilename =
    'updates/[id].[hash].hot-update.js';
  serverConfig.module.rules = serverConfig.module.rules.filter(
    x => x.loader !== 'null-loader',
  );
  serverConfig.plugins.push(new webpack.HotModuleReplacementPlugin());

  // Configure compilation
  await run(clean);
  const multiCompiler = webpack(webpackConfig);
  const clientCompiler = multiCompiler.compilers.find(
    compiler => compiler.name === 'client',
  );
  const serverCompiler = multiCompiler.compilers.find(
    compiler => compiler.name === 'server',
  );
  const clientPromise = createCompilationPromise(
    'client',
    clientCompiler,
    clientConfig,
  );
  const serverPromise = createCompilationPromise(
    'server',
    serverCompiler,
    serverConfig,
  );

  // https://github.com/webpack/webpack-dev-middleware
  server.use(
    webpackDevMiddleware(clientCompiler, {
      publicPath: clientConfig.output.publicPath,
      logLevel: 'silent',
      watchOptions,
    }),
  );

  // https://github.com/glenjamin/webpack-hot-middleware
  server.use(webpackHotMiddleware(clientCompiler, { log: false }));

  let appPromise;
  let appPromiseResolve;
  let appPromiseIsResolved = true;
  serverCompiler.hooks.compile.tap('server', () => {
    if (!appPromiseIsResolved) return;
    appPromiseIsResolved = false;
    // eslint-disable-next-line no-return-assign
    appPromise = new Promise(resolve => (appPromiseResolve = resolve));
  });

  let app;
  server.use((req, res) => {
    appPromise
      .then(() => app.handle(req, res))
      .catch(error => console.error(error));
  });

  function checkForUpdate(fromUpdate) {
    const hmrPrefix = '[\x1b[35mHMR\x1b[0m] ';
    if (!app.hot) {
      throw new Error(`${hmrPrefix}Hot Module Replacement is disabled.`);
    }
    if (app.hot.status() !== 'idle') {
      return Promise.resolve();
    }
    return app.hot
      .check(true)
      .then(updatedModules => {
        if (!updatedModules) {
          if (fromUpdate) {
            console.info(`${hmrPrefix}Update applied.`);
          }
          return;
        }
        if (updatedModules.length === 0) {
          console.info(`${hmrPrefix}Nothing hot updated.`);
        } else {
          console.info(`${hmrPrefix}Updated modules:`);
          updatedModules.forEach(moduleId =>
            console.info(`${hmrPrefix} - ${moduleId}`),
          );
          checkForUpdate(true);
        }
      })
      .catch(error => {
        if (['abort', 'fail'].includes(app.hot.status())) {
          console.warn(`${hmrPrefix}Cannot apply update.`);
          delete require.cache[require.resolve('../build/server')];
          // eslint-disable-next-line global-require, import/no-unresolved
          app = require('../build/server').default;
          console.warn(`${hmrPrefix}App has been reloaded.`);
        } else {
          console.warn(
            `${hmrPrefix}Update failed: ${error.stack || error.message}`,
          );
        }
      });
  }

  serverCompiler.watch(watchOptions, (error, stats) => {
    if (app && !error && !stats.hasErrors()) {
      checkForUpdate().then(() => {
        appPromiseIsResolved = true;
        appPromiseResolve();
      });
    }
  });

  // Wait until both client-side and server-side bundles are ready
  await clientPromise;
  await serverPromise;

  const timeStart = new Date();
  console.info(`[${format(timeStart)}] Launching server...`);

  // Load compiled src/server.js as a middleware
  // eslint-disable-next-line global-require, import/no-unresolved
  app = require('../build/server').default;
  appPromiseIsResolved = true;
  appPromiseResolve();

  // Launch the development server with Browsersync and HMR
  await new Promise((resolve, reject) =>
    browserSync.create().init(
      {
        // https://www.browsersync.io/docs/options
        server: 'src/server.js',
        middleware: [server],
        open: !process.argv.includes('--silent'),
        ...(isDebug ? {} : { notify: false, ui: false }),
      },
      (error, bs) => (error ? reject(error) : resolve(bs)),
    ),
  );

  const timeEnd = new Date();
  const time = timeEnd.getTime() - timeStart.getTime();
  console.info(`[${format(timeEnd)}] Server launched after ${time} ms`);
  return server;
}
1199548
function startClient(httpBackend, client) {
    httpBackend.when("GET", "/pushrules").respond(200, {});
    httpBackend.when("POST", "/filter").respond(200, { filter_id: "fid" });
    httpBackend.when("GET", "/sync").respond(200, INITIAL_SYNC_DATA);

    client.startClient();

    // set up a promise which will resolve once the client is initialised
    const deferred = Promise.defer();
    client.on("sync", function(state) {
        console.log("sync", state);
        if (state != "SYNCING") {
            return;
        }
        deferred.resolve();
    });

    return Promise.all([
        httpBackend.flushAllExpected(),
        deferred.promise,
    ]);
}
1252494
function PushRoute (router, request, scheme, handler, limits, validate, upload) {
		let args = [scheme, limits], filt = v=>!!v;
		args = (!!validate ? args.concat([validate]).filter(filt) : args);
		args = (!!upload   ? args.concat([upload  ]).filter(filt) : args);
		args = args.concat([handler]); router[request](...args);
	}
377810
function makeHttpRequest(next) {
  var start = Date.now();

  sepia.fixtureDir(path.join(process.cwd(), 'fixtures/custom'));

  request({
    url: 'http://localhost:1337',
    method: 'GET'
  }, function(err, data, body) {
    var time = Date.now() - start;

    console.log('FIXTURE DIR');
    console.log('  status:', data.statusCode);
    console.log('  body  :', body);
    console.log('  time  :', time);

    common.verify(function() {
      fs.existsSync('fixtures/custom').should.equal(true);
      common.shouldBeDynamicallyTimed(time);
    });

    console.log();

    next();
  });
}
980059
function _preServiceCall({ node, type, preStatus, callerId, shouldDumpStoreOnActionCall }, payload) {
    //There is a problem if the node is empty. //Node should be an array
    let data = {};
    let status = {};
    const STATUS = { name: preStatus, isLoading: true };
    type = shouldDumpStoreOnActionCall ? 'update' : 'updateStatus';
    // When there is a multi node update it should be an array.
    if (Array.isArray(node)) {
        node.forEach((nd) => {
            data[nd] = shouldDumpStoreOnActionCall ? null : (payload && payload[nd]) || null;
            status[nd] = STATUS;
        });
    } else {
        data[node] = shouldDumpStoreOnActionCall ? null : (payload || null);
        status[node] = STATUS;
    }
    //Dispatch store cleaning.
    dispatcher.handleViewAction({ data, type, status, callerId });
}
862050
function serveErr(_req, res, next) {
    return async function (err) {
        if (err.message === 'next') {
            return next();
        }
        console.log('ERROR', err);
        console.log('STACK', err.stack);
        let text = 'ERROR' + (err.code ? ' ' + err.code : '') + ': ' + err.message;
        exports.globalOpts.serveErr.propertiesWhiteList.forEach(function (attrName) {
            if (attrName in err) {
                text += '\n' + attrName + ': ' + JSON.stringify(err[attrName]);
            }
        });
        if (exports.globalOpts.serveErr.sendStack) {
            text += '\n------------------\n' + err.stack;
        }
        if (!res.headersSent) {
            let buf = new Buffer(text);
            let length = buf.length;
            res.writeHead(err.status || 400, {
                'Content-Length': length,
                'Content-Type': 'text/plain; charset=utf-8'
            });
        }
        else {
            text += "\n</script>\n<pre>\n------------------------------------\n" + text;
        }
        res.end(text);
    };
}
1034227
function ZeroPushErrorStatus(response) {
  MessagingServiceStatus.call(this, 'zeropush');

  // There was an error when attempting to send message
  this.state.message = response.name + ': ' + response.message;

  if (response.name === 'InvalidPayloadError') this.state.code = this.StatusCodes.DATA_REJECTED;
  else this.state.code = this.StatusCodes.DEFAULT;
}
149524
function handlePushError(pushError, pushHandler) {
    return Platform.async(function(callback) {
        callback();
    })().then(function() {
        
        if (pushError.isConflict()) {
            if (pushHandler && pushHandler.onConflict) {
                // NOTE: value of server record will not be available in case of 409.
                return pushHandler.onConflict(pushError);
            }
        } else if (pushHandler && pushHandler.onError) {
            return pushHandler.onError(pushError);
        }

    }).then(undefined, function(error) {
        // Set isHandled to false even if the user has set it to handled if the onConflict / onError failed 
        pushError.isHandled = false;
    });
}
402230
async function initModule (ravelInstance) {
  const self = this;
  const name = Metadata.getClassMetaValue(Object.getPrototypeOf(self), '@role', 'name');
  // run @postinject handlers
  const postInjects = Metadata.getClassMeta(Object.getPrototypeOf(self), '@postinject', Object.create(null));
  await Promise.all(Object.keys(postInjects).map(f => postInjects[f].call(self)));
  // connect any Ravel lifecycle handlers to the appropriate events
  function connectHandlers (decorator, event) {
    const handlers = Metadata.getClassMeta(Object.getPrototypeOf(self), decorator, Object.create(null));
    for (const f of Object.keys(handlers)) {
      ravelInstance.once(event, (...args) => {
        ravelInstance.$log.trace(`${name}: Invoking ${decorator} ${f}`);
        handlers[f].apply(self, args);
      });
    }
  }
  connectHandlers('@postinit', 'post init');
  connectHandlers('@prelisten', 'pre listen');
  connectHandlers('@koaconfig', 'pre routes init');
  connectHandlers('@postlisten', 'post listen');
  connectHandlers('@preclose', 'end');

  // connect @interval
  const handlers = Metadata.getClassMeta(Object.getPrototypeOf(self), '@interval', Object.create(null));
  const intervals = [];
  ravelInstance.once('post listen', () => {
    for (const f of Object.keys(handlers)) {
      intervals.push(setInterval(() => {
        ravelInstance.$log.trace(`${name}: Invoking @interval ${f}`);
        handlers[f].handler.call(self);
      }, handlers[f].interval));
    }
  });
  ravelInstance.once('end', () => {
    intervals.forEach((i) => clearInterval(i));
  });

  // register middleware
  const middleware = Metadata.getClassMeta(Object.getPrototypeOf(self), '@middleware', Object.create(null));
  ravelInstance.once('post module init', () => {
    for (const m of Object.keys(middleware)) {
      if (ravelInstance[symbols.moduleFactories][m]) {
        throw new $err.DuplicateEntry(
          `Unable to register @middleware with name ${m}, which conflicts with an existing Module name`);
      } else {
        ravelInstance.$log.info(`Registering middleware with name ${m}`);
        ravelInstance[symbols.middleware][m] = middleware[m].bind(self);
      }
    }
  });
}
474527
function determineProvider (req, res, next) {
  var providerID = req.params.provider || req.body.provider
  if (providerID && settings.providers[providerID]) {
    req.provider = providers[providerID]
  }
  next()
}
1260087
function PubNubTransport(config) {
  this.id = config.id || null;
  this.networkId = config.publish_key || null;
  this['default'] = config['default'] || false;
  this.pubnub = PUBNUB().init(config);
}
139293
function cachePush(value) {
    var cache = this.cache,
        type = typeof value;

    if (type == 'boolean' || value == null) {
      cache[value] = true;
    } else {
      if (type != 'number' && type != 'string') {
        type = 'object';
      }
      var key = type == 'number' ? value : keyPrefix + value,
          typeCache = cache[type] || (cache[type] = {});

      if (type == 'object') {
        (typeCache[key] || (typeCache[key] = [])).push(value);
      } else {
        typeCache[key] = true;
      }
    }
  }
1274157
function (host, port, prefix, suffix, globalize, cacheDns, mock,
    globalTags, maxBufferSize, bufferFlushInterval, telegraf, sampleRate, protocol) {
  let options = host || {};
  const self = this;

  // Adding options below is DEPRECATED.  Use the options object instead.
  if (arguments.length > 1 || typeof(host) === 'string') {
    options = {
      host        : host,
      port        : port,
      prefix      : prefix,
      suffix      : suffix,
      globalize   : globalize,
      cacheDns    : cacheDns,
      mock        : mock === true,
      globalTags  : globalTags,
      maxBufferSize : maxBufferSize,
      bufferFlushInterval: bufferFlushInterval,
      telegraf    : telegraf,
      sampleRate  : sampleRate,
      protocol    : protocol
    };
  }

  const createSocket = function createSocket(instance, args) {
    let socket;
    let errMessage;

    if (args.protocol === 'tcp') {
      try {
        socket = net.connect(args.port, args.host);
        socket.setKeepAlive(true);
      } catch (e) {
        errMessage = `Could not establish connection to ${args.host}:${args.port}`;
        if (instance.errorHandler) {
          instance.errorHandler(new Error(errMessage));
        } else {
          console.log(errMessage);
        }
      }
    } else {
      socket = dgram.createSocket('udp4');
    }

    return socket;
  };

  // hidden global_tags option for backwards compatibility
  options.globalTags = options.globalTags || options.global_tags;

  this.protocol    = (options.protocol && options.protocol.toLowerCase());
  this.host        = options.host || process.env.DD_AGENT_HOST || 'localhost';
  this.port        = options.port || parseInt(process.env.DD_DOGSTATSD_PORT, 10) || 8125;
  this.prefix      = options.prefix || '';
  this.suffix      = options.suffix || '';
  this.socket      = options.isChild ? options.socket : createSocket(this, {
    host: this.host,
    port: this.port,
    protocol: this.protocol
  });
  this.mock        = options.mock;
  this.globalTags  = typeof options.globalTags === 'object' ?
      helpers.formatTags(options.globalTags, options.telegraf) : [];
  if (process.env.DD_ENTITY_ID) {
    this.globalTags = this.globalTags.filter((item) => {
      return item.indexOf('dd.internal.entity_id:') !== 0;
   });
    this.globalTags.push('dd.internal.entity_id:'.concat(helpers.sanitizeTags(process.env.DD_ENTITY_ID)));
  }
  this.telegraf    = options.telegraf || false;
  this.maxBufferSize = options.maxBufferSize || 0;
  this.sampleRate  = options.sampleRate || 1;
  this.bufferFlushInterval = options.bufferFlushInterval || 1000;
  this.bufferHolder = options.isChild ? options.bufferHolder : { buffer: '' };
  this.errorHandler = options.errorHandler;

  // If we're mocking the client, create a buffer to record the outgoing calls.
  if (this.mock) {
    this.mockBuffer = [];
  }

  // We only want a single flush event per parent and all its child clients
  if (!options.isChild && this.maxBufferSize > 0) {
    this.intervalHandle = setInterval(this.onBufferFlushInterval.bind(this), this.bufferFlushInterval);
  }

  if (options.isChild) {
    if (options.dnsError) {
      this.dnsError = options.dnsError;
    }
  } else if (options.cacheDns === true) {
    dns.lookup(options.host, (err, address) => {
      if (err === null) {
        self.host = address;
      } else {
        self.dnsError = err;
      }
    });
  }

  if (!options.isChild && options.errorHandler) {
    this.socket.on('error', options.errorHandler);
  }

  if (options.globalize) {
    global.statsd = this;
  }

  if (options.useDefaultRoute) {
    const defaultRoute = helpers.getDefaultRoute();
    if (defaultRoute) {
      console.log(`Got ${defaultRoute} for the system's default route`);
      this.host = defaultRoute;
    }
  }

  this.messagesInFlight = 0;
  this.CHECKS = {
    OK: 0,
    WARNING: 1,
    CRITICAL: 2,
    UNKNOWN: 3,
  };
}