<commit_before>import _ from 'lodash';

export function getPlatformName(platformType) {
  var options = {
    'spa': 'Single Page App',
    'native-mobile': 'Native Mobile App',
    'webapp': 'Regular Web Application',
    'hybrid': 'Hybrid Mobile App',
    'backend': 'Backend/API'
  };

  return options[platformType];
}

export function getQuestion(platformType) {
  platformType = platformType || 'none';
  var questions = {
    'none': 'Getting started? Try our quickstarts.',
    'spa': 'What technology will you use in the FrontEnd?',
    'native-mobile': 'Select a native SDK',
    'webapp': 'What technology are you using for your WebApp?',
    'hybrid': 'Select a Hybrid SDK',
    'backend': 'Select an API or Backend platform'
  };

  return questions[platformType];
}

export function getPlatformSlug(platformType) {
  var paths = {
    'spa': 'client-platforms',
    'native-mobile': 'native-platforms',
    'webapp': 'server-platforms',
    'hybrid': 'native-platforms',
    'backend': 'server-apis'
  };

  return paths[platformType];
}

export function getPlatformCollection(quickstart, platformType) {
  if(!platformType) {
    return [];
  }

  var options = {
    'spa': quickstart.clientPlatforms,
    'native-mobile': quickstart.nativePlatforms,
    'webapp': quickstart.serverPlatforms,
    'hybrid': quickstart.hybridPlatforms,
    'backend': quickstart.serverApis
  };

  return options[platformType];
}

export function getTechTitle(quickstart, appType, techName) {
  var collection = getPlatformCollection(quickstart, appType);

  var result = _.find(collection, { name: techName });

  if(result) {
    return result.title;
  }
}

export function getQuickstartMetdata(quickstart, appType, tech1, tech2) {
  var meta = {};
  if (appType && tech1 && tech2) {
    if (tech2 === 'no-api') {
      meta.pageTitle = `${getTechTitle(quickstart, appType, tech1)} Quickstart`;
      meta.pageDescription = `Learn how to quickly add authentication to your ${getTechTitle(quickstart, appType, tech1)} app. Authenticate with any social or enterprise identity provider.`;
    } else {
      meta.pageTitle = `${getTechTitle(quickstart, appType, tech1)} + ${getTechTitle(quickstart, 'backend', tech2)} Quickstart`;
      meta.pageDescription = `Learn how to quickly add authentication to your ${getTechTitle(quickstart, appType, tech1)} app that connects to ${getTechTitle(quickstart, 'backend', tech2)}. Authenticate with any social or enterprise identity provider.`;
    }

  } else if (appType && tech1) {
    meta.pageTitle = `${getTechTitle(quickstart, appType, tech1)} Quickstarts`;
    meta.pageDescription =  `Learn how to quickly add authentication to your ${getTechTitle(quickstart, appType, tech1)} app. Authenticate with any social or enterprise identity provider.`;
  } else if (appType) {
    meta.pageTitle = `${getPlatformName(appType)} Quickstarts`;
    meta.pageDescription = `Browse ${getPlatformName(appType).toLowerCase()} quickstarts to learn how to quickly add authentication to your app.`;
  } else {
    meta.pageTitle = process.env.SITE_TITLE;
  }
  return meta;
}

export function loadArticle(payload) {
  var url = `${payload.baseUrl || ''}/${getPlatformSlug(payload.appType)}/` +
         `${payload.currentTech}?${payload.appType}=${payload.tech1}&e=1`;
  if(payload.tech2) {
   url += '&api=' + payload.tech2;
  }

  if(payload.clientId) {
   url += '&a=' + payload.clientId;
  }

  function checkStatus(response) {
   if (response.status >= 200 && response.status < 400) {
     return response;
   } else {
     var error = new Error(response.statusText);
     error.status = response.status;
     error.response = response;
     throw error;
   }
  }

  return window.fetch(url, {
   credentials: 'include'
  })
  .then(checkStatus)
  .then(function(response) {
   return response.text();
  });
};
<commit_msg>Delete Tutorials.js<commit_after><|endoftext|>


<commit_before>var cluster = require("cluster");
var os = require('os');
var path = require("path");

var Message = require(path.join(__dirname, 'message'));
var Worker = require(path.join(__dirname, 'worker'));
var Shared = require(path.join(__dirname, 'shared'));

var numCPUs = require("os").cpus().length;

var Async = function(){
  var workers = [];
  var currentWorker = -1;
  var swapFile = path.join(os.tmpdir(), ('__npc-' + process.pid + '.swap'));

  var shared = new Shared({
    'swap': swapFile,
  });

  cluster.setupMaster({
    exec: path.join(__dirname, 'worker.js')
  });

  for (var cpuNum = 0; cpuNum < numCPUs; cpuNum += 1){

    var worker = new Worker({
      'shared': shared,
      'onMessage': function(msg){
        //console.log('master #' + process.pid + ' rec\'d message from slave #' + this.process.pid + ':', msg);

        //var msg = new Message();
        //msg.setPayload('ping', Shared.ping.master_message);
        //this.process.send(msg);
      }
    });
    workers.push(worker);

  };

  return {
    shared: shared,

    executeAction: function(id, args, options){
      var options = options || {};
      var workerIndex = ++currentWorker % workers.length;
      var msg = new Message();
      msg.setPayload('action', {
        'id': id,
        'arguments': args || [],
        'options': options || {},
      });
      workers[workerIndex].send(msg);
    }

  };

};

module.exports = Async(); // it's a module!
<commit_msg>allow execution of actions on-the-fly<commit_after>var cluster = require("cluster");
var os = require('os');
var path = require("path");

var Message = require(path.join(__dirname, 'message'));
var Worker = require(path.join(__dirname, 'worker'));
var Shared = require(path.join(__dirname, 'shared'));

var numCPUs = require("os").cpus().length;

var Async = function(){
  var workers = [];
  var currentWorker = -1;
  var swapFile = path.join(os.tmpdir(), ('__npc-' + process.pid + '.swap'));

  var shared = new Shared({
    'swap': swapFile,
  });

  cluster.setupMaster({
    exec: path.join(__dirname, 'worker.js')
  });

  for (var cpuNum = 0; cpuNum < numCPUs; cpuNum += 1){

    var worker = new Worker({
      'shared': shared,
      'onMessage': function(msg){
        //console.log('master #' + process.pid + ' rec\'d message from slave #' + this.process.pid + ':', msg);

        //var msg = new Message();
        //msg.setPayload('ping', Shared.ping.master_message);
        //this.process.send(msg);
      }
    });
    workers.push(worker);

  };

  return {
    shared: shared,

    executeAction: function(id, args, options){
      var options = options || {};
      var workerIndex = ++currentWorker % workers.length;
      var msg = new Message();
      msg.setPayload('action', {
        'id': id,
        'arguments': args || [],
        'options': options || {},
      });
      workers[workerIndex].send(msg);
    },

    executeFunction: function(func, args, options){
      actionName = process.pid.toString() +
        '-' + Math.round(Math.random() * 10e15).toString(36);

      this.shared.set(actionName, func);
      this.executeAction(actionName, args, options);
    }

  };

};

module.exports = Async(); // it's a module!
<|endoftext|>


<commit_before>const logLinkErrs = require('../config.js').log.linkErrs
const connectDb = require('../util/connectDatabase.js')
const log = require('../util/logger.js')
const FeedFetcher = require('../util/FeedFetcher.js')
const RequestError = require('../structs/errors/RequestError.js')
const FeedParserError = require('../structs/errors/FeedParserError.js')
const LinkLogic = require('../structs/LinkLogic.js')
const debug = require('../util/debugFeeds.js')
const DataDebugger = require('../structs/DataDebugger.js')
const databaseFuncs = require('../util/database.js')

async function fetchFeed (headers, url, debug) {
  if (debug) {
    log.debug.info(`${url}: Fetching URL`)
  }
  const fetchOptions = {}
  if (headers) {
    if (!headers.lastModified || !headers.etag) {
      throw new Error(`Headers exist for a link, but missing lastModified and etag (${url})`)
    }
    fetchOptions.headers = {
      'If-Modified-Since': headers.lastModified,
      'If-None-Match': headers.etag
    }
  }
  const { stream, response } = await FeedFetcher.fetchURL(url, fetchOptions)
  if (response.status === 304) {
    if (debug) {
      log.debug.info(`${url}: 304 response, sending success status`)
    }
    return null
  } else {
    const lastModified = response.headers['last-modified']
    const etag = response.headers['etag']

    if (lastModified && etag) {
      process.send({
        status: 'headers',
        link: url,
        lastModified,
        etag
      })
      if (debug) {
        log.debug.info(`${url}: Sending back headers`)
      }
    }
    return stream
  }
}

async function parseStream (stream, url, debug) {
  if (debug) {
    log.debug.info(`${url}: Parsing stream`)
  }
  const { articleList } = await FeedFetcher.parseStream(stream, url)
  if (articleList.length === 0) {
    if (debug) {
      log.debug.info(`${url}: No articles found, sending success status`)
    }
    return null
  }
  return articleList
}

async function syncDatabase (articleList, databaseDocs, feeds, meta, memoryCollection) {
  const allComparisons = new Set()
  for (const feedID in feeds) {
    const feed = feeds[feedID]
    feed.ncomparisons.forEach(v => allComparisons.add(v))
    feed.pcomparisons.forEach(v => allComparisons.add(v))
  }
  const {
    toInsert,
    toUpdate
  } = await databaseFuncs.getInsertsAndUpdates(
    articleList,
    databaseDocs,
    Array.from(allComparisons),
    meta
  )

  await databaseFuncs.insertDocuments(toInsert, memoryCollection)
  await databaseFuncs.updateDocuments(toUpdate, memoryCollection)
}

async function getFeed (data) {
  const { link, rssList, headers, toDebug, docs, feedData, shardID, scheduleName } = data
  try {
    const stream = await fetchFeed(headers[link], link, toDebug)
    if (!stream) {
      process.send({ status: 'success', link })
      return
    }
    const articleList = await parseStream(stream, link, toDebug)
    if (!articleList) {
      process.send({ status: 'success', link })
      return
    }
    // Sync first
    const meta = {
      feedURL: link,
      shardID,
      scheduleName
    }
    await syncDatabase(articleList, docs, rssList, meta, feedData)

    // Then send to prevent new article spam if sync fails
    const logic = new LinkLogic({ articleList, ...data })
    const result = await logic.run(docs)
    const newArticles = result.newArticles
    const length = newArticles.length
    for (let i = 0; i < length; ++i) {
      if (toDebug) {
        log.debug.info(`${link}: Sending article status`)
      }
      process.send({
        status: 'article',
        article: newArticles[i]
      })
    }
    process.send({
      status: 'success',
      link,
      memoryCollection: feedData
    })
  } catch (err) {
    if (toDebug) {
      log.debug.info(`${link}: Sending failed status`)
    }
    process.send({ status: 'failed', link, rssList })
    if (err instanceof RequestError || err instanceof FeedParserError) {
      if (logLinkErrs || toDebug) {
        log.cycle.warning(`Skipping ${link}`, err)
      }
    } else {
      log.cycle.error(`Cycle logic (${link})`, err, true)
    }
  }
}

process.on('message', async m => {
  const currentBatch = m.currentBatch
  const { debugFeeds, debugLinks, scheduleName, shardID, feedData } = m
  debug.feeds = new DataDebugger(debugFeeds || [], 'feeds-processor')
  debug.links = new DataDebugger(debugLinks || [], 'links-processor')
  try {
    await connectDb(true)
    const articleDocuments = await databaseFuncs.getAllDocuments(shardID, scheduleName, feedData)
    const promises = []
    for (const link in currentBatch) {
      const docs = articleDocuments[link] || []
      const toDebug = debug.links.has(link)
      if (toDebug) {
        log.debug.info(`${link}: Isolated processor received link in batch`)
      }
      const rssList = currentBatch[link]
      promises.push(getFeed({ ...m, link, rssList, toDebug, docs }))
    }
    await Promise.all(promises)
    process.exit()
  } catch (err) {
    log.general.error(`processor`, err)
  }
})
<commit_msg>Restore/fix config.feeds.sendOldOnFirsyCycle function<commit_after>const logLinkErrs = require('../config.js').log.linkErrs
const connectDb = require('../util/connectDatabase.js')
const log = require('../util/logger.js')
const FeedFetcher = require('../util/FeedFetcher.js')
const RequestError = require('../structs/errors/RequestError.js')
const FeedParserError = require('../structs/errors/FeedParserError.js')
const LinkLogic = require('../structs/LinkLogic.js')
const debug = require('../util/debugFeeds.js')
const DataDebugger = require('../structs/DataDebugger.js')
const databaseFuncs = require('../util/database.js')
const config = require('../config.js')

async function fetchFeed (headers, url, debug) {
  if (debug) {
    log.debug.info(`${url}: Fetching URL`)
  }
  const fetchOptions = {}
  if (headers) {
    if (!headers.lastModified || !headers.etag) {
      throw new Error(`Headers exist for a link, but missing lastModified and etag (${url})`)
    }
    fetchOptions.headers = {
      'If-Modified-Since': headers.lastModified,
      'If-None-Match': headers.etag
    }
  }
  const { stream, response } = await FeedFetcher.fetchURL(url, fetchOptions)
  if (response.status === 304) {
    if (debug) {
      log.debug.info(`${url}: 304 response, sending success status`)
    }
    return null
  } else {
    const lastModified = response.headers['last-modified']
    const etag = response.headers['etag']

    if (lastModified && etag) {
      process.send({
        status: 'headers',
        link: url,
        lastModified,
        etag
      })
      if (debug) {
        log.debug.info(`${url}: Sending back headers`)
      }
    }
    return stream
  }
}

async function parseStream (stream, url, debug) {
  if (debug) {
    log.debug.info(`${url}: Parsing stream`)
  }
  const { articleList } = await FeedFetcher.parseStream(stream, url)
  if (articleList.length === 0) {
    if (debug) {
      log.debug.info(`${url}: No articles found, sending success status`)
    }
    return null
  }
  return articleList
}

async function syncDatabase (articleList, databaseDocs, feeds, meta, memoryCollection) {
  const allComparisons = new Set()
  for (const feedID in feeds) {
    const feed = feeds[feedID]
    feed.ncomparisons.forEach(v => allComparisons.add(v))
    feed.pcomparisons.forEach(v => allComparisons.add(v))
  }
  const {
    toInsert,
    toUpdate
  } = await databaseFuncs.getInsertsAndUpdates(
    articleList,
    databaseDocs,
    Array.from(allComparisons),
    meta
  )

  await databaseFuncs.insertDocuments(toInsert, memoryCollection)
  await databaseFuncs.updateDocuments(toUpdate, memoryCollection)
}

async function getFeed (data) {
  const { link, rssList, headers, toDebug, docs, feedData, shardID, scheduleName, runNum } = data
  try {
    const stream = await fetchFeed(headers[link], link, toDebug)
    if (!stream) {
      process.send({ status: 'success', link })
      return
    }
    const articleList = await parseStream(stream, link, toDebug)
    if (!articleList) {
      process.send({ status: 'success', link })
      return
    }
    // Sync first
    const meta = {
      feedURL: link,
      shardID,
      scheduleName
    }
    await syncDatabase(articleList, docs, rssList, meta, feedData)

    if (runNum !== 0 || config.feeds.sendOldOnFirstCycle === true) {
      // Then send to prevent new article spam if sync fails
      const logic = new LinkLogic({ articleList, ...data })
      const result = await logic.run(docs)
      const newArticles = result.newArticles
      const length = newArticles.length
      for (let i = 0; i < length; ++i) {
        if (toDebug) {
          log.debug.info(`${link}: Sending article status`)
        }
        process.send({
          status: 'article',
          article: newArticles[i]
        })
      }
    }

    process.send({
      status: 'success',
      link,
      memoryCollection: feedData
    })
  } catch (err) {
    if (toDebug) {
      log.debug.info(`${link}: Sending failed status`)
    }
    process.send({ status: 'failed', link, rssList })
    if (err instanceof RequestError || err instanceof FeedParserError) {
      if (logLinkErrs || toDebug) {
        log.cycle.warning(`Skipping ${link}`, err)
      }
    } else {
      log.cycle.error(`Cycle logic (${link})`, err, true)
    }
  }
}

process.on('message', async m => {
  const currentBatch = m.currentBatch
  const { debugFeeds, debugLinks, scheduleName, shardID, feedData } = m
  debug.feeds = new DataDebugger(debugFeeds || [], 'feeds-processor')
  debug.links = new DataDebugger(debugLinks || [], 'links-processor')
  try {
    await connectDb(true)
    const articleDocuments = await databaseFuncs.getAllDocuments(shardID, scheduleName, feedData)
    const promises = []
    for (const link in currentBatch) {
      const docs = articleDocuments[link] || []
      const toDebug = debug.links.has(link)
      if (toDebug) {
        log.debug.info(`${link}: Isolated processor received link in batch`)
      }
      const rssList = currentBatch[link]
      promises.push(getFeed({ ...m, link, rssList, toDebug, docs }))
    }
    await Promise.all(promises)
    process.exit()
  } catch (err) {
    log.general.error(`processor`, err)
  }
})
<|endoftext|>


<commit_before>var Joi = require('joi');

var models = module.exports = {};

models.Application = {
  tableName: 'applications',
  hashKey: 'appId',
  schema: {
    appId: Joi.string(),
    orgId: Joi.string().required(),
    created: Joi.date().default(Date.now, 'created'),
    updated: Joi.date().default(Date.now, 'updated'),
    ownerId: Joi.string().required(),
    domainName: Joi.string(),
    subDomain: Joi.string(),
    requireSsl: Joi.boolean().default(false),
    trafficControlEnabled: Joi.boolean().default(false),
    // deployments is a Map where the top level keys are the env names and the values
    // is an array of traffic rules. Each rule consists of a version attribute and a rule
    // attribute.
    trafficRules: Joi.object().pattern(/[a-z]+/, Joi.array(Joi.object().keys({
      version: Joi.string(),
      rule: Joi.string()
    }))).default({}),

    // Addon specific settings. The keys in the object is the name of the addon.
    addOnSettings: Joi.object().pattern(/[a-z]+/, Joi.object()).default({}),
    env: Joi.object().default({})
  },
  indexes: [
    {
      name: 'orgIdIndex',
      type: 'global',
      hashKey: 'orgId',
      projection: {
        ProjectionType: 'KEYS_ONLY'
      }
    },
    {
      name: 'ownerIdIndex',
      type: 'global',
      hashKey: 'ownerId',
      projection: {
        ProjectionType: 'KEYS_ONLY'
      }
    },
    {
      name: 'domainNameIndex',
      type: 'global',
      hashKey: 'domainName',
      rangeKey: 'subDomain',
      projection: {
        ProjectionType: 'KEYS_ONLY'
      }
    }
  ]
};

models.User = {
  tableName: 'users',
  hashKey: 'userId',
  schema: {
    userId: Joi.string(),
    providerUserId: Joi.string().required(),
    username: Joi.string().required(),
    provider: Joi.string().required(),
    email: Joi.string(),
    avatar: Joi.string(),
    defaultOrgId: Joi.string(),
    lastLogin: Joi.date(),
    joined: Joi.date().default(Date.now, 'joined')
  },
  indexes: [
    {
      name: 'providerUserIndex',
      hashKey: 'providerUserId',
      rangeKey: 'provider',
      type: 'global'
    }
  ]
};

models.Organization = {
  tableName: 'organizations',
  hashKey: 'orgId',
  schema: {
    orgId: Joi.string(),
    name: Joi.string().required(),
    createdDate: Joi.date().default(Date.now, 'createdDate'),
    activatedDate: Joi.date(),
    activated: Joi.boolean().default(false),
    terminated: Joi.boolean().default(false),
    terminationDate: Joi.date(),
    terminatedBy: Joi.string(),
    ownerId: Joi.string(),
    source: Joi.string(), // Value like 'bitbucket', 'aerobatic', etc.

    addOnSettings: Joi.object().pattern(/[a-z]+/, Joi.object()).default({}),

    // Default environment pipeline as an ordered list
    // Apps can only be promoted in this order
    environments: Joi.array(Joi.string())
  }
};

models.OrgMember = {
  tableName: 'orgMembers',
  hashKey: 'orgId',
  rangeKey: 'userId',
  schema: {
    orgId: Joi.string(),
    userId: Joi.string(),
    created: Joi.date().default(Date.now, 'joined'),
    role: Joi.string().required()
  },
  indexes: [
    {
      name: 'userIdIndex',
      type: 'global',
      hashKey: 'userId'
    }
  ]
};

models.Domain = {
  tableName: 'appDomains',
  hashKey: 'domainName',
  timestamps: true,
  schema: {
    domainName: Joi.string(),
    orgId: Joi.string().required(),
    certificateId: Joi.string(),
    cdnDistributionId: Joi.string(),
    status: Joi.string(),
    dnsValue: Joi.string()
  },
  indexes: [
    {
      name: 'orgIdIndex',
      type: 'global',
      hashKey: 'orgId'
    }
  ]
};

models.LegacyDomain = {
  tableName: 'domains',
  hashKey: 'domain',
  schema: {
    domain: Joi.string(),
    appId: Joi.string(),
    action: Joi.string().allow('resolve', 'redirect').default('resolve'),
    orgId: Joi.string().required(),
    certificateId: Joi.string(),
    certificate: Joi.string(),
    zone: Joi.string() // corresponds to something like a CDN distribution
  },
  indexes: [
    {
      name: 'appIdIndex',
      hashKey: 'appId',
      type: 'global'
    },
    {
      name: 'orgIdIndex',
      hashKey: 'orgId',
      type: 'global'
    }
  ]
};

models.AppName = {
  tableName: 'appName',
  hashKey: 'name',
  schema: {
    name: Joi.string(),
    appId: Joi.string().required()
  },
  indexes: [
    {
      name: 'appIdIndex',
      type: 'global',
      hashKey: 'appId'
    }
  ]
};

models.Version = {
  tableName: 'versions',
  hashKey: 'appId',
  rangeKey: 'versionId',
  schema: {
    appId: Joi.string(),
    versionId: Joi.string(),
    versionNum: Joi.number(),
    name: Joi.string().required(),
    userId: Joi.string().required(),
    created: Joi.date().default(Date.now, 'created'),
    duration: Joi.number(),
    message: Joi.string(),
    status: Joi.string().required().valid(['initiated', 'complete', 'failed', 'timedOut']),
    commit: Joi.string(),
    fileCount: Joi.number(),

    // The version error if status is 'failed'
    error: Joi.string(),

    // The JSON app manifest for this version
    manifest: Joi.object().required(),
    deploymentParts: Joi.array(Joi.object())
  },
  indexes: [
    {
      name: 'appIdVersionNumIndex',
      type: 'local',
      hashKey: 'appId',
      rangeKey: 'versionNum',
      projection: {
        NonKeyAttributes: ['name', 'userId', 'created', 'message', 'status', 'error'],
        ProjectionType: 'INCLUDE'
      }
    }
  ]
};

models.DailyOperations = {
  tableName: 'dailyOperations',
  hashKey: 'orgId',
  rangeKey: 'dateAppId', // example 2015-03-appid
  schema: {
    orgId: Joi.string(),
    dateAppId: Joi.string(),
    appId: Joi.string(),
    total: Joi.number()
    // Additional attributes are created on the fly with names like "op_html-page, op_api-proxy, etc
    // that hold the count of the number of times that operation was invoked.
  },
  indexes: [
    {
      name: 'appIdIndex',
      type: 'global',
      hashKey: 'appId',
      rangeKey: 'dateAppId'
    }
  ]
};

// Generic table for holding key/values where the value is itself a key/value map
models.KeyValueMap = {
  tableName: 'keyValueMap',
  hashKey: 'key',
  schema: {
    key: Joi.string(),
    value: Joi.object().pattern(/[a-z]+/, Joi.object()).default({}),
    createdDate: Joi.date().default(Date.now, 'createdDate')
  }
};

// Audit trail of actions taken including things like: app created, app deleted,
// version deployed, version promoted, version rolled back
// models.AuditTrail = {
//   tableName: 'auditTrail',
//   hashKey: 'orgId',
//   rangeKey: 'timestamp',
//
//   schema: {
//     appId: Joi.string(),
//     versionId: Joi.string(),
//     action: Joi.string(), // created, promoted, rolledback, softLaunch
//     userId: Joi.string(),
//     timestamp: Joi.date().default(Date.now, 'timestamp')
//   }
// };
<commit_msg>Add a hasLog attribute to Version model<commit_after>var Joi = require('joi');

var models = module.exports = {};

models.Application = {
  tableName: 'applications',
  hashKey: 'appId',
  schema: {
    appId: Joi.string(),
    orgId: Joi.string().required(),
    created: Joi.date().default(Date.now, 'created'),
    updated: Joi.date().default(Date.now, 'updated'),
    ownerId: Joi.string().required(),
    domainName: Joi.string(),
    subDomain: Joi.string(),
    requireSsl: Joi.boolean().default(false),
    trafficControlEnabled: Joi.boolean().default(false),
    // deployments is a Map where the top level keys are the env names and the values
    // is an array of traffic rules. Each rule consists of a version attribute and a rule
    // attribute.
    trafficRules: Joi.object().pattern(/[a-z]+/, Joi.array(Joi.object().keys({
      version: Joi.string(),
      rule: Joi.string()
    }))).default({}),

    // Addon specific settings. The keys in the object is the name of the addon.
    addOnSettings: Joi.object().pattern(/[a-z]+/, Joi.object()).default({}),
    env: Joi.object().default({})
  },
  indexes: [
    {
      name: 'orgIdIndex',
      type: 'global',
      hashKey: 'orgId',
      projection: {
        ProjectionType: 'KEYS_ONLY'
      }
    },
    {
      name: 'ownerIdIndex',
      type: 'global',
      hashKey: 'ownerId',
      projection: {
        ProjectionType: 'KEYS_ONLY'
      }
    },
    {
      name: 'domainNameIndex',
      type: 'global',
      hashKey: 'domainName',
      rangeKey: 'subDomain',
      projection: {
        ProjectionType: 'KEYS_ONLY'
      }
    }
  ]
};

models.User = {
  tableName: 'users',
  hashKey: 'userId',
  schema: {
    userId: Joi.string(),
    providerUserId: Joi.string().required(),
    username: Joi.string().required(),
    provider: Joi.string().required(),
    email: Joi.string(),
    avatar: Joi.string(),
    defaultOrgId: Joi.string(),
    lastLogin: Joi.date(),
    joined: Joi.date().default(Date.now, 'joined')
  },
  indexes: [
    {
      name: 'providerUserIndex',
      hashKey: 'providerUserId',
      rangeKey: 'provider',
      type: 'global'
    }
  ]
};

models.Organization = {
  tableName: 'organizations',
  hashKey: 'orgId',
  schema: {
    orgId: Joi.string(),
    name: Joi.string().required(),
    createdDate: Joi.date().default(Date.now, 'createdDate'),
    activatedDate: Joi.date(),
    activated: Joi.boolean().default(false),
    terminated: Joi.boolean().default(false),
    terminationDate: Joi.date(),
    terminatedBy: Joi.string(),
    ownerId: Joi.string(),
    source: Joi.string(), // Value like 'bitbucket', 'aerobatic', etc.

    addOnSettings: Joi.object().pattern(/[a-z]+/, Joi.object()).default({}),

    // Default environment pipeline as an ordered list
    // Apps can only be promoted in this order
    environments: Joi.array(Joi.string())
  }
};

models.OrgMember = {
  tableName: 'orgMembers',
  hashKey: 'orgId',
  rangeKey: 'userId',
  schema: {
    orgId: Joi.string(),
    userId: Joi.string(),
    created: Joi.date().default(Date.now, 'joined'),
    role: Joi.string().required()
  },
  indexes: [
    {
      name: 'userIdIndex',
      type: 'global',
      hashKey: 'userId'
    }
  ]
};

models.Domain = {
  tableName: 'appDomains',
  hashKey: 'domainName',
  timestamps: true,
  schema: {
    domainName: Joi.string(),
    orgId: Joi.string().required(),
    certificateId: Joi.string(),
    cdnDistributionId: Joi.string(),
    status: Joi.string(),
    dnsValue: Joi.string()
  },
  indexes: [
    {
      name: 'orgIdIndex',
      type: 'global',
      hashKey: 'orgId'
    }
  ]
};

models.LegacyDomain = {
  tableName: 'domains',
  hashKey: 'domain',
  schema: {
    domain: Joi.string(),
    appId: Joi.string(),
    action: Joi.string().allow('resolve', 'redirect').default('resolve'),
    orgId: Joi.string().required(),
    certificateId: Joi.string(),
    certificate: Joi.string(),
    zone: Joi.string() // corresponds to something like a CDN distribution
  },
  indexes: [
    {
      name: 'appIdIndex',
      hashKey: 'appId',
      type: 'global'
    },
    {
      name: 'orgIdIndex',
      hashKey: 'orgId',
      type: 'global'
    }
  ]
};

models.AppName = {
  tableName: 'appName',
  hashKey: 'name',
  schema: {
    name: Joi.string(),
    appId: Joi.string().required()
  },
  indexes: [
    {
      name: 'appIdIndex',
      type: 'global',
      hashKey: 'appId'
    }
  ]
};

models.Version = {
  tableName: 'versions',
  hashKey: 'appId',
  rangeKey: 'versionId',
  schema: {
    appId: Joi.string(),
    versionId: Joi.string(),
    versionNum: Joi.number(),
    name: Joi.string().required(),
    userId: Joi.string().required(),
    created: Joi.date().default(Date.now, 'created'),
    duration: Joi.number(),
    message: Joi.string(),
    status: Joi.string().required().valid(['initiated', 'complete', 'failed', 'timedOut']),
    commit: Joi.string(),
    hasLog: Joi.boolean().default(false),
    fileCount: Joi.number(),

    // The version error if status is 'failed'
    error: Joi.string(),

    // The JSON app manifest for this version
    manifest: Joi.object().required(),
    deploymentParts: Joi.array(Joi.object())
  },
  indexes: [
    {
      name: 'appIdVersionNumIndex',
      type: 'local',
      hashKey: 'appId',
      rangeKey: 'versionNum',
      projection: {
        NonKeyAttributes: ['name', 'userId', 'created', 'message', 'status', 'error'],
        ProjectionType: 'INCLUDE'
      }
    }
  ]
};

models.DailyOperations = {
  tableName: 'dailyOperations',
  hashKey: 'orgId',
  rangeKey: 'dateAppId', // example 2015-03-appid
  schema: {
    orgId: Joi.string(),
    dateAppId: Joi.string(),
    appId: Joi.string(),
    total: Joi.number()
    // Additional attributes are created on the fly with names like "op_html-page, op_api-proxy, etc
    // that hold the count of the number of times that operation was invoked.
  },
  indexes: [
    {
      name: 'appIdIndex',
      type: 'global',
      hashKey: 'appId',
      rangeKey: 'dateAppId'
    }
  ]
};

// Generic table for holding key/values where the value is itself a key/value map
models.KeyValueMap = {
  tableName: 'keyValueMap',
  hashKey: 'key',
  schema: {
    key: Joi.string(),
    value: Joi.object().pattern(/[a-z]+/, Joi.object()).default({}),
    createdDate: Joi.date().default(Date.now, 'createdDate')
  }
};

// Audit trail of actions taken including things like: app created, app deleted,
// version deployed, version promoted, version rolled back
// models.AuditTrail = {
//   tableName: 'auditTrail',
//   hashKey: 'orgId',
//   rangeKey: 'timestamp',
//
//   schema: {
//     appId: Joi.string(),
//     versionId: Joi.string(),
//     action: Joi.string(), // created, promoted, rolledback, softLaunch
//     userId: Joi.string(),
//     timestamp: Joi.date().default(Date.now, 'timestamp')
//   }
// };
<|endoftext|>


<commit_before>/**
 * @file Platform Function. Support identification system, engine, browser type
 * @author wupeng10
 */

define(function () {
    'use strict';
    /**
     * Browser user agent
     *
     * @type {Obejct}
     * @public
     */
    var ua = navigator.userAgent;

    /**
     * Browser app version
     *
     * @type {string}
     * @public
     */
    var nver = navigator.appVersion;

    /**
     * OS type
     *
     * @type {Object}
     * @public
     */
    var system = {
        isIos: false,
        isAndroid: false
    };

    /**
     * Browser type
     *
     * @type {Object}
     * @public
     */
    var browser = {
        isUc: false,
        isChrome: false,
        isAdr: false,
        isSafari: false,
        isQQ: false,
        isSamsung: false,
        isFireFox: false,
        isBaidu: false,
        isBaiduApp: false
    };

    /**
     * Browser engine type
     *
     * @type {Object}
     * @public
     */
    var engine = {
        isTrident: false,
        isGecko: false,
        isWebkit: false
    };

    /**
     * Judge system, iOS, android
     *
     */
    if (/iPhone|iPad|iPod/i.test(ua)) {
        system.isIos = true;
    } else if (/Android/i.test(ua)) {
        system.isAndroid = true;
    }

    /**
     * Judge browser type
     *
     */
    if (/UCBrowser/i.test(ua)) {
        browser.isUc = true;
    } else if (/baidubrowser/i.test(ua)) {
        browser.isBaidu = true;
    } else if (/baiduboxapp/i.test(ua)) {
        browser.isBaiduApp = true;
    } else if (/qqbrowser\/([0-9.]+)/i.test(ua)) {
        browser.isQQ = true;
    } else if (/android/i.test(ua) && /\bversion\/([0-9.]+(?: beta)?)/i.test(ua)) { // Need to put before chrome
        browser.isAdr = true;
    } else if (/\bversion\/([0-9.]+(?: beta)?)(?: mobile(?:\/[a-z0-9]+)?)? safari\//i.test(ua)) {
        browser.isSafari = true;
    } else if (/samsung/i.test(ua) || /android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i.test(ua) || /((SM-T\w+))/i.test(ua)) {
        browser.isSamsung = true;
    } else if (/ (?:chrome|crios|crmo)\/([0-9.]+)/i.test(ua)) {
        browser.isChrome = true;
    } else if (/\bfirefox\/([0-9.ab]+)/i.test(ua) || /FxiOS+\/([0-9.ab]+)/i.test(ua)) {
        browser.isFireFox = true;
    }

    /**
     * Judge browser engine type
     *
     */
    if (/\b(?:msie |ie |trident\/[0-9].*rv[ :])([0-9.]+)/i.test(ua)) {
        engine.isTrident = true;
    } else if (/\brv:([\d\w.]+).*\bgecko\/(\d+)/i.test(ua)) {
        engine.isGecko = true;
    } else if (/\bapplewebkit[\/]?([0-9.+]+)/i.test(ua)) {
        engine.isWebkit = true;
    }

    /**
     * OS Version
     *
     * @return {string}
     */
    function getOsVersion() {
        var osVersion;
        if (this.isAndroid()) {
            osVersion = /Android ([\.\_\d]+)/.exec(ua)[1];
        } else if (this.isIos()) {
            osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nver);
            osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
        }
        return osVersion;
    }

    /**
     * Package result
     *
     */
    var result = [system, engine, browser];
    var data = {
        'getOsVersion': getOsVersion,
        'needSpecialScroll':system.isIos && window != top
    };
    for (var i = 0; i < result.length; i++) {
        for (var key in result[i]) {
            data[key] = (function (key) {
                return function () {
                    return key;
                }
            })(result[i][key])
        }
    }

    return data;
});<commit_msg>update<commit_after>/**
 * @file Platform Function. Support identification system, engine, browser type
 * @author wupeng10
 */

define(function () {
    'use strict';
    /**
     * Browser user agent
     *
     * @type {Obejct}
     * @public
     */
    var ua = navigator.userAgent;

    /**
     * Browser app version
     *
     * @type {string}
     * @public
     */
    var nver = navigator.appVersion;

    /**
     * OS type
     *
     * @type {Object}
     * @public
     */
    var system = {
        isIos: false,
        isAndroid: false
    };

    /**
     * Browser type
     *
     * @type {Object}
     * @public
     */
    var browser = {
        isUc: false,
        isChrome: false,
        isAdr: false,
        isSafari: false,
        isQQ: false,
        isSamsung: false,
        isFireFox: false,
        isBaidu: false,
        isBaiduApp: false
    };

    /**
     * Browser engine type
     *
     * @type {Object}
     * @public
     */
    var engine = {
        isTrident: false,
        isGecko: false,
        isWebkit: false
    };

    /**
     * Judge system, iOS, android
     *
     */
    if (/iPhone|iPad|iPod/i.test(ua)) {
        system.isIos = true;
    } else if (/Android/i.test(ua)) {
        system.isAndroid = true;
    }

    /**
     * Judge browser type
     *
     */
    if (/UCBrowser/i.test(ua)) {
        browser.isUc = true;
    } else if (/baidubrowser/i.test(ua)) {
        browser.isBaidu = true;
    } else if (/baiduboxapp/i.test(ua)) {
        browser.isBaiduApp = true;
    } else if (/qqbrowser\/([0-9.]+)/i.test(ua)) {
        browser.isQQ = true;
    } else if (/android/i.test(ua) && /\bversion\/([0-9.]+(?: beta)?)/i.test(ua)) { // Need to put before chrome
        browser.isAdr = true;
    } else if (/\bversion\/([0-9.]+(?: beta)?)(?: mobile(?:\/[a-z0-9]+)?)? safari\//i.test(ua)) {
        browser.isSafari = true;
    } else if (/samsung/i.test(ua) || /android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n\d+|sgh-t8[56]9|nexus 10))/i.test(ua) || /((SM-T\w+))/i.test(ua)) {
        browser.isSamsung = true;
    } else if (/ (?:chrome|crios|crmo)\/([0-9.]+)/i.test(ua)) {
        browser.isChrome = true;
    } else if (/\bfirefox\/([0-9.ab]+)/i.test(ua) || /FxiOS+\/([0-9.ab]+)/i.test(ua)) {
        browser.isFireFox = true;
    }

    /**
     * Judge browser engine type
     *
     */
    if (/\b(?:msie |ie |trident\/[0-9].*rv[ :])([0-9.]+)/i.test(ua)) {
        engine.isTrident = true;
    } else if (/\brv:([\d\w.]+).*\bgecko\/(\d+)/i.test(ua)) {
        engine.isGecko = true;
    } else if (/\bapplewebkit[\/]?([0-9.+]+)/i.test(ua)) {
        engine.isWebkit = true;
    }

    /**
     * OS Version
     *
     * @return {string}
     */
    function getOsVersion() {
        var osVersion;
        if (this.isAndroid()) {
            osVersion = /Android ([\.\_\d]+)/.exec(ua)[1];
        } else if (this.isIos()) {
            osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nver);
            osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
        }
        return osVersion;
    }

    /**
     * Package result
     *
     */
    var result = [system, engine, browser];
    var data = {
        'getOsVersion': getOsVersion,
        'needSpecialScroll':system.isIos && window != top
    };
    for (var i = 0; i < result.length; i++) {
        for (var key in result[i]) {
            var handle = function(key) {
                return key;
            }.bind(null, result[i][key]);
            data[key] = handle;
        }
    }

    return data;
});<|endoftext|>


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

module.exports = function DesignupModule(moduleOptions) {
  this.addPlugin(path.resolve(__dirname, './plugins/font-awesome.js'))
  this.addPlugin(path.resolve(__dirname, './plugins/plugin.js'))
  this.options.css.push('normalize.css/normalize.css')

  if (!Array.isArray(this.options.build.postcss)) {
    this.options.build.postcss = []
  }

  this.options.build.postcss.push(
    require('postcss-preset-env')({
      stage: 0,
      features: {
        'custom-properties': {
          preserve: false,
          variables: require('./../src/variables/variables')({
            theme: moduleOptions.theme || 'blue'
          })
        },
        'custom-media-queries': {
          extensions: require('./../src/variables/custom-media')
        }
      }
    })
  )
  this.options.css.push(path.resolve(__dirname, '../src/styles/modules.css'))
}

module.exports.meta = require('./../package.json')
<commit_msg>Updated module<commit_after>const path = require('path')

module.exports = function DesignupModule(moduleOptions) {
  this.addPlugin(path.resolve(__dirname, './plugins/font-awesome.js'))
  this.addPlugin(path.resolve(__dirname, './plugins/plugin.js'))
  this.options.css.push('normalize.css/normalize.css')

  if (!Array.isArray(this.options.build.postcss)) {
    this.options.build.postcss = []
  }

  this.options.build.postcss.push(
    require('postcss-preset-env')({
      stage: 0,
      preserve: false,
      importFrom: [
        {
          customProperties: require('./../src/variables/variables')({
            theme: moduleOptions.theme || 'blue'
          }),
          customMedia: require('./../src/variables/custom-media')
        }
      ],
      features: {
        'color-mod-function': {
          unresolved: 'ignore'
        }
      }
    })
  )
  this.options.css.push(path.resolve(__dirname, '../src/styles/modules.css'))
}

module.exports.meta = require('./../package.json')
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint nomen:true, node:true*/

/**
Main module in the Mojito package that is responsible for creating the mojito
instance to the attached to the `express` app.

Developers should not access this module directly, but instead should
instantiate their app the `express` way.

Usage:

    var app = require('express'),
        mojito = require('mojito'),
        app;

    app = express(); // Mojito instance will be created during that call

    app.use(mojito.middleware()); // register the Mojito specific middleware

    app.post('/tunnel', mojito.tunnelMiddleware()); // setup tunnel dispatcher

    app.mojito.attachRoutes(); // load routes defined in `routes.json`

    // setup other routes here

    app.listen(app.get('port'));

@module mojito
**/

'use strict';

var debug = require('debug')('mojito'),
    express = require('express'),
    libann = require('express-annotations'),
    libmap = require('express-map'),
    libpath = require('path'),
    appProto = express.application,
    defaultConfiguration = appProto.defaultConfiguration,
    libdispatcher = require('./dispatcher'),
    liblogger = require('./logger'),
    libmiddleware = require('./middleware'),
    librouter = require('./router'),
    libstore = require('./store'),
    libtunnel = require('./tunnel'),
    extend = require('./util').extend,
    Mojito;

//  ----------------------------------------------------------------------------
//  Mojito Global
//  ----------------------------------------------------------------------------

/**
Mojito extension for Express.

@protected
@class Mojito
@constructor
@param {express.application} app `express` application instance
@uses *express, dispatcher, logger, middleware, router, store, tunnel
**/
function Mojito(app) {

    // FIXME: This might not be required since app.js would have already
    // required this.
    libann.extend(app);
    libmap.extend(app);

    this._app = app;
    this._config = {};
    extend(Mojito, libdispatcher, liblogger, libmiddleware, libtunnel);
    app.mojito = {};
    this._init(app);

    return this;
}

/**
Creates a new instance of mojito and attach to `app`.

@method _init
@protected
@param {express.application} app optional

**/
Mojito.prototype._init = function (app) {

    app = app || this._app;

    var context = {},
        appConfig,      // application.json
        options = {},   //
        store;          // reference to resource store

    // debug('applying mojito.defaultConfiguration()');

    if (!app.mojito) {
        throw new Error('`app.mojito` was not initialized correctly.');
    }

    // TODO: use correct static context here
    context.runtime = 'server';

    options = {};
    options.port = process.env.PORT || appConfig.appPort || 8666;
    options.context = context;
    options.mojitoRoot = __dirname;
    // TODO: `root` is required for the resource store, which will be replaced
    // by `locator` at some point. `locator` will have access to the appRoot
    // folder.
    // The application root directory
    options.root = process.cwd();

    appConfig = libstore.getAppConfig(options.root, context);
    options.Y = this._createYUIInstance(options, appConfig);
    liblogger.configureLogger(options.Y);
    store = libstore.createStore(options);
    this._configureAppInstance(app, store, options, appConfig);

    // set port from application.json
    app.set('port', options.port);
};

/**
Configures YUI with both the Mojito framework and all the YUI modules in the
application.

@method _configureYUI
@protected
@param {Object} Y YUI object to configure
@param {Object} store Resource Store which knows what to load
@return {Array} array of YUI module names
**/
Mojito.prototype._configureYUI = function (Y, store) {
    var my = this,
        modules,
        load,
        lang;

    modules = store.yui.getModulesConfig('server', false);
    Y.applyConfig(modules);

    load = Object.keys(modules.modules);

    // NOTE:  Not all of these module names are guaranteed to be valid,
    // but the loader tolerates them anyways.
    for (lang in store.yui.langs) {
        if (store.yui.langs.hasOwnProperty(lang) && lang) {
            load.push('lang/datatype-date-format_' + lang);
        }
    }

    return load;
};

/**
Creates the YUI instance used by the server.

@method _createYUIInstance
@protected
@param {Object} options Same as the `options` parameter to `_configureAppInstance()`.
@param {Object} appConfig The static configuration for the application.
*/
Mojito.prototype._createYUIInstance = function (options, appConfig) {
    var yuiConfig,
        modules = [],
        Y;

    yuiConfig = (appConfig.yui && appConfig.yui.config) || {};

    // redefining "combine" and/or "base" in the server side have side effects
    // and might try to load yui from CDN, so we bypass them.
    // TODO: report bug.
    // is there a better alternative for this delete?
    // maybe not, but it might introduce a perf penalty
    // in v8 engine, and we can't use the undefined trick
    // because loader is doing hasOwnProperty :(
    delete yuiConfig.combine;
    delete yuiConfig.base;

    // in case we want to collect some performance metrics,
    // we can do that by defining the "perf" object in:
    // application.json (master)
    // You can also use the option --perf path/filename.log when
    // running mojito start to dump metrics to disk.
    if (appConfig.perf) {
        yuiConfig.perf = appConfig.perf;
        yuiConfig.perf.logFile = options.perf || yuiConfig.perf.logFile;
    }

    // getting yui module, or yui/debug if needed, and applying
    // the default configuration from application.json->yui-config
    Y = require('yui' + (yuiConfig.filter === 'debug' ? '/debug' : '')).YUI(yuiConfig, {
        useSync: true
    });

    return Y;
};

/**
Adds Mojito framework components to the Express application instance.

@method _configureAppInstance
@protected
@param {express.application} app The Express application instance to Mojito-enable.
@param {ResourceStore} store
@param {Object} options
    @param {Integer} options.port port to listen on
    @param {Object} options.context static context set at startup
    @param {String} options.mojitoRoot
    @param {String} options.root the app root dir
@param {Object} appConfig The static configuration for the application.
**/
Mojito.prototype._configureAppInstance = function (app, store, options, appConfig) {
    var Y = options.Y,
        modules = [];

    modules = this._configureYUI(Y, store);

    // attaching all modules available for this application for the server side
    Y.applyConfig({ useSync: true });
    Y.use.apply(Y, modules);
    Y.applyConfig({ useSync: false });

    // TODO: This might change when `express-yui` and `locator` are integrated
    // and how they are exposed to the `app.mojito` instance.
    // stash for runtime
    extend(app.mojito, {
        store: store,
        Y: Y,
        context: options.context,
        options: options,
        _app: app, // reference to `app` from within `app.mojito`
        attachRoutes: librouter.attachRoutes
    });

    console.log('✔\tMojito ready to serve.');

}; // _configureAppInstance

/**
Hook into `express` default configuration init phase.
**/
appProto.defaultConfiguration = function () {
    defaultConfiguration.apply(this, arguments);

    if (!this.mojito) {
        var mojito = new Mojito(this);
    } else {
        debug('skipping creation of `app.mojito` because it is already defined');
    }
};

//  ----------------------------------------------------------------------------
//  EXPORT(S)
//  ----------------------------------------------------------------------------

/**

Export Mojito extension as a function.

**/

module.exports = Mojito;

<commit_msg>Updated from PR feedback<commit_after>/**
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint nomen:true, node:true*/

/**
Main module in the Mojito package that is responsible for creating the mojito
instance to the attached to the `express` app.

Developers should not access this module directly, but instead should
instantiate their app the `express` way.

Usage:

    var app = require('express'),
        mojito = require('mojito'),
        app;

    app = express(); // Mojito instance will be created during that call

    app.use(mojito.middleware()); // register the Mojito specific middleware

    app.post('/tunnel', mojito.tunnelMiddleware()); // setup tunnel dispatcher

    app.mojito.attachRoutes(); // load routes defined in `routes.json`

    // setup other routes here

    app.listen(app.get('port'));

@module mojito
**/

'use strict';

var debug = require('debug')('mojito'),
    express = require('express'),
    libann = require('express-annotations'),
    libmap = require('express-map'),
    libpath = require('path'),
    appProto = express.application,
    defaultConfiguration = appProto.defaultConfiguration,
    libdispatcher = require('./dispatcher'),
    liblogger = require('./logger'),
    libmiddleware = require('./middleware'),
    librouter = require('./router'),
    libstore = require('./store'),
    libtunnel = require('./tunnel'),
    extend = require('./util').extend,
    Mojito;

//  ----------------------------------------------------------------------------
//  Mojito Global
//  ----------------------------------------------------------------------------

/**
Mojito extension for Express.

@protected
@class Mojito
@constructor
@param {express.application} app `express` application instance
@uses *express, dispatcher, logger, middleware, router, store, tunnel
**/
function Mojito(app) {

    libann.extend(app);
    libmap.extend(app);

    this._app = app;
    this._config = {};
    extend(Mojito, libdispatcher, liblogger, libmiddleware, libtunnel);
    app.mojito = {};
    this._init(app);

    return this;
}

/**
Creates a new instance of mojito and attach to `app`.

@method _init
@protected
@param {express.application} app optional

**/
Mojito.prototype._init = function (app) {

    app = app || this._app;

    var context = {},
        appConfig,      // application.json
        options = {},   //
        store;          // reference to resource store

    // debug('applying mojito.defaultConfiguration()');

    if (!app.mojito) {
        throw new Error('`app.mojito` was not initialized correctly.');
    }

    // TODO: use correct static context here
    context.runtime = 'server';

    options = {};
    options.port = process.env.PORT || appConfig.appPort || 8666;
    options.context = context;
    options.mojitoRoot = __dirname;
    // TODO: `root` is required for the resource store, which will be replaced
    // by `locator` at some point. `locator` will have access to the appRoot
    // folder.
    // The application root directory
    options.root = process.cwd();

    appConfig = libstore.getAppConfig(options.root, context);
    options.Y = this._createYUIInstance(options, appConfig);
    liblogger.configureLogger(options.Y);
    store = libstore.createStore(options);
    this._configureAppInstance(app, store, options, appConfig);

    // set port from application.json
    app.set('port', options.port);
};

/**
Configures YUI with both the Mojito framework and all the YUI modules in the
application.

@method _configureYUI
@protected
@param {Object} Y YUI object to configure
@param {Object} store Resource Store which knows what to load
@return {Array} array of YUI module names
**/
Mojito.prototype._configureYUI = function (Y, store) {
    var my = this,
        modules,
        load,
        lang;

    modules = store.yui.getModulesConfig('server', false);
    Y.applyConfig(modules);

    load = Object.keys(modules.modules);

    // NOTE:  Not all of these module names are guaranteed to be valid,
    // but the loader tolerates them anyways.
    for (lang in store.yui.langs) {
        if (store.yui.langs.hasOwnProperty(lang) && lang) {
            load.push('lang/datatype-date-format_' + lang);
        }
    }

    return load;
};

/**
Creates the YUI instance used by the server.

@method _createYUIInstance
@protected
@param {Object} options Same as the `options` parameter to `_configureAppInstance()`.
@param {Object} appConfig The static configuration for the application.
*/
Mojito.prototype._createYUIInstance = function (options, appConfig) {
    var yuiConfig,
        modules = [],
        Y;

    yuiConfig = (appConfig.yui && appConfig.yui.config) || {};

    // redefining "combine" and/or "base" in the server side have side effects
    // and might try to load yui from CDN, so we bypass them.
    // TODO: report bug.
    // is there a better alternative for this delete?
    // maybe not, but it might introduce a perf penalty
    // in v8 engine, and we can't use the undefined trick
    // because loader is doing hasOwnProperty :(
    delete yuiConfig.combine;
    delete yuiConfig.base;

    // in case we want to collect some performance metrics,
    // we can do that by defining the "perf" object in:
    // application.json (master)
    // You can also use the option --perf path/filename.log when
    // running mojito start to dump metrics to disk.
    if (appConfig.perf) {
        yuiConfig.perf = appConfig.perf;
        yuiConfig.perf.logFile = options.perf || yuiConfig.perf.logFile;
    }

    // getting yui module, or yui/debug if needed, and applying
    // the default configuration from application.json->yui-config
    Y = require('yui' + (yuiConfig.filter === 'debug' ? '/debug' : '')).YUI(yuiConfig, {
        useSync: true
    });

    return Y;
};

/**
Adds Mojito framework components to the Express application instance.

@method _configureAppInstance
@protected
@param {express.application} app The Express application instance to Mojito-enable.
@param {ResourceStore} store
@param {Object} options
    @param {Integer} options.port port to listen on
    @param {Object} options.context static context set at startup
    @param {String} options.mojitoRoot
    @param {String} options.root the app root dir
@param {Object} appConfig The static configuration for the application.
**/
Mojito.prototype._configureAppInstance = function (app, store, options, appConfig) {
    var Y = options.Y,
        modules = [];

    modules = this._configureYUI(Y, store);

    // attaching all modules available for this application for the server side
    Y.applyConfig({ useSync: true });
    Y.use.apply(Y, modules);
    Y.applyConfig({ useSync: false });

    // TODO: This might change when `express-yui` and `locator` are integrated
    // and how they are exposed to the `app.mojito` instance.
    // stash for runtime
    extend(app.mojito, {
        store: store,
        Y: Y,
        context: options.context,
        options: options,
        _app: app, // reference to `app` from within `app.mojito`
        attachRoutes: librouter.attachRoutes
    });

    console.log('✔\tMojito ready to serve.');

}; // _configureAppInstance

/**
Hook into `express` default configuration init phase.
**/
appProto.defaultConfiguration = function () {
    defaultConfiguration.apply(this, arguments);

    if (!this.mojito) {
        var mojito = new Mojito(this);
    } else {
        debug('skipping creation of `app.mojito` because it is already defined');
    }
};

//  ----------------------------------------------------------------------------
//  EXPORT(S)
//  ----------------------------------------------------------------------------

/**

Export Mojito extension as a function.

**/

module.exports = Mojito;

<|endoftext|>


<commit_before>import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";

export default {
  input: "src/index.js",
  output: {
    file: "dist/milsymbol.development.js",
    format: "umd"
  },
  name: "ms",
  plugins: [resolve(), commonjs()]
};
<commit_msg>Make sure the AMD module is named "milsymbol"<commit_after>import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";

export default {
  input: "src/index.js",
  output: {
    file: "dist/milsymbol.development.js",
    format: "umd",
    amd: {
      id: "milsymbol"
    }
  },
  name: "ms",
  plugins: [resolve(), commonjs()]
};
<|endoftext|>


<commit_before>const body = require("utils_body_constants");
const roles = require("utils_role_constants");
var createName = require("utils_naming")

var spawner = Game.spawns['Gubbins'];
var sources = spawner.room.find(FIND_SOURCES);
var availableEnergy = spawner.store.getUsedCapacity(RESOURCE_ENERGY);

function spawnHarvester() {
    sources.forEach(function(srs){
        var tmp = spawner.room.find(FIND_MY_CREEPS, {filter: (s) => s.memory.source == srs.id})
        if(tmp == ''){
            targetSource = srs.id;
        }
        });

        var bodyPieces = [MOVE, CARRY];
        var cost = body.MOVE.cost + body.CARRY.cost;
        while(cost + body.WORK.cost <= availableEnergy){
            bodyPieces.push(WORK);
            cost += body.WORK.cost;
        }

        var code = spawner.spawnCreep(bodyPieces, createName(roles.HARVEST), {memory: {role: roles.HARVEST, source: targetSource}});
        console.log('Spawning new harvester: ' + code);
        return;
}

function spawnBuilder() {

    var bodyPieces = [MOVE, MOVE, WORK];
    var cost = body.MOVE.cost * 2 + body.WORK.cost;
    while(cost + body.CARRY.cost <= availableEnergy){
        bodyPieces.push(CARRY);
        cost += body.CARRY.cost;
    }
    var code = spawner.spawnCreep(bodyPieces, createName(roles.BUILD), {memory: {role: roles.BUILD}});
    console.log('Spawning new builder: ' + code);
    return;
}

function spawnUpgrader() {
    var bodyPieces = [WORK, CARRY, MOVE];
            var code = spawner.spawnCreep(bodyPieces, createName(roles.UPGRADE), {memory: {role: roles.UPGRADE}});
            console.log('Spawning new upgrader: ' + code);
            return;
}

function spawnHauler() {
    var bodyPieces = [MOVE, CARRY];
    var cost = body.MOVE.cost + body.CARRY.cost;
    while(cost + body.WORK.cost + body.CARRY.cost <= availableEnergy){
        bodyPieces.push(WORK);
        bodyPieces.push(CARRY);
        cost += body.WORK.cost + body.CARRY.cost;
    }
    var code = spawner.spawnCreep(bodyPieces, createName(roles.HAUL), {memory: {role: roles.HAUL}});
    console.log('Spawning new hauler: ' + code);
    return;
}
module.exports = {
    spawnBuilder,
    spawnHarvester,
    spawnHauler,
    spawnUpgrader
}<commit_msg>Fixed indenting issue causing -6 error when spawning upgraders<commit_after>const body = require("utils_body_constants");
const roles = require("utils_role_constants");
var createName = require("utils_naming")

var spawner = Game.spawns['Gubbins'];
var sources = spawner.room.find(FIND_SOURCES);
var availableEnergy = spawner.store.getUsedCapacity(RESOURCE_ENERGY);

function spawnHarvester() {
    sources.forEach(function(srs){
        var tmp = spawner.room.find(FIND_MY_CREEPS, {filter: (s) => s.memory.source == srs.id})
        if(tmp == ''){
            targetSource = srs.id;
        }
        });

        var bodyPieces = [MOVE, CARRY];
        var cost = body.MOVE.cost + body.CARRY.cost;
        while(cost + body.WORK.cost <= availableEnergy){
            bodyPieces.push(WORK);
            cost += body.WORK.cost;
        }

        var code = spawner.spawnCreep(bodyPieces, createName(roles.HARVEST), {memory: {role: roles.HARVEST, source: targetSource}});
        console.log('Spawning new harvester: ' + code);
        return;
}

function spawnBuilder() {

    var bodyPieces = [MOVE, MOVE, WORK];
    var cost = body.MOVE.cost * 2 + body.WORK.cost;
    while(cost + body.CARRY.cost <= availableEnergy){
        bodyPieces.push(CARRY);
        cost += body.CARRY.cost;
    }
    var code = spawner.spawnCreep(bodyPieces, createName(roles.BUILD), {memory: {role: roles.BUILD}});
    console.log('Spawning new builder: ' + code);
    return;
}

function spawnUpgrader() {
    var bodyPieces = [WORK, CARRY, MOVE];
    var code = spawner.spawnCreep(bodyPieces, createName(roles.UPGRADE), {memory: {role: roles.UPGRADE}});
    console.log('Spawning new upgrader: ' + code);
    return;
}

function spawnHauler() {
    var bodyPieces = [MOVE, CARRY];
    var cost = body.MOVE.cost + body.CARRY.cost;
    while(cost + body.WORK.cost + body.CARRY.cost <= availableEnergy){
        bodyPieces.push(WORK);
        bodyPieces.push(CARRY);
        cost += body.WORK.cost + body.CARRY.cost;
    }
    var code = spawner.spawnCreep(bodyPieces, createName(roles.HAUL), {memory: {role: roles.HAUL}});
    console.log('Spawning new hauler: ' + code);
    return;
}
module.exports = {
    spawnBuilder,
    spawnHarvester,
    spawnHauler,
    spawnUpgrader
}<|endoftext|>


<commit_before>import { createPlugins } from "rollup-plugin-atomic"
import TerserOptions from "./.terserrc.js"

const plugins = createPlugins([
  "js",
  "babel",
  "json",
  ["terser", TerserOptions],
  // "visualizer",
])

const RollupConfig = [
  {
    input: "lib/main.js",
    output: [
      {
        dir: "dist",
        format: "cjs",
        sourcemap: true,
        preferConst: true,
      },
    ],
    // loaded externally
    external: ["atom", "electron"],
    plugins,
  },
]
export default RollupConfig
<commit_msg>chore: inline sourcemaps in dev mode<commit_after>import { createPlugins } from "rollup-plugin-atomic"
import TerserOptions from "./.terserrc.js"

const plugins = createPlugins([
  "js",
  "babel",
  "json",
  ["terser", TerserOptions],
  // "visualizer",
])

const RollupConfig = [
  {
    input: "lib/main.js",
    output: [
      {
        dir: "dist",
        format: "cjs",
        sourcemap: process.env.NODE_ENV !== "production" ? "inline" : true,
        preferConst: true,
      },
    ],
    // loaded externally
    external: ["atom", "electron"],
    plugins,
  },
]
export default RollupConfig
<|endoftext|>


<commit_before>'use strict';

const Promise = require('bluebird');
const _ = require('lodash');
const exec = require('child_process').exec;
const split = require('split');

const ACCEPTED_OPTIONS = [
  'cwd',
  'env',
  'shell',
  'timeout',
  'maxBuffer',
  'killSignal',
  'uid',
  'gid'
];

module.exports = (state) => new Promise((resolve, reject) => {
  const options = _.reduce(ACCEPTED_OPTIONS, (result, value) => _.set(result, value, state.get(value)), {});
  const child = exec(state.get('command'), options, (err, stdout) => {
    if (err) {
      reject(err);
    }
    resolve(stdout);
  });
  child.stdout
    .pipe(split())
    .on('data', line => {
      if (line) {
        state.logger.info(line);
      }
    });
  child.stderr
    .pipe(split())
    .on('data', line => {
      if (line) {
        state.logger.error({message: line});
      }
    });
});
<commit_msg>Adding shell command logging<commit_after>'use strict';

const Promise = require('bluebird');
const _ = require('lodash');
const exec = require('child_process').exec;
const split = require('split');

const ACCEPTED_OPTIONS = [
  'cwd',
  'env',
  'shell',
  'timeout',
  'maxBuffer',
  'killSignal',
  'uid',
  'gid'
];

module.exports = (state) => new Promise((resolve, reject) => {
  const options = _.reduce(ACCEPTED_OPTIONS, (result, value) => _.set(result, value, state.get(value)), {});
  state.logger.info(`Executing: ${state.get('command')}`);
  const child = exec(state.get('command'), options, (err, stdout) => {
    if (err) {
      reject(err);
    }
    resolve(stdout);
  });
  child.stdout
    .pipe(split())
    .on('data', line => {
      if (line) {
        state.logger.info(line);
      }
    });
  child.stderr
    .pipe(split())
    .on('data', line => {
      if (line) {
        state.logger.error({message: line});
      }
    });
});
<|endoftext|>


<commit_before>const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const babel = require('rollup-plugin-babel');
const replace = require('rollup-plugin-replace');
const uglify = require('rollup-plugin-uglify');

const format = process.env.BABEL_ENV;
const production = process.env.NODE_ENV === 'production';

const babelPlugins = ['external-helpers'];
if (production) {
  babelPlugins.push('transform-react-remove-prop-types');
}

const plugins = [
  commonjs({
    include: 'node_modules/**',
  }),
  babel({
    babelrc: false,
    exclude: 'node_modules/**',
    presets: [
      ['env', {
        targets: {
          browsers: ['last 2 versions', 'safari > 7'],
        },
        modules: false,
      }],
      'stage-0',
      'react',
    ],
    plugins: babelPlugins,
  }),
  resolve({
    jsnext: true,
    main: true,
    browser: true,
  }),
  replace({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
  }),
];

if (production) {
  plugins.push(uglify());
}

export default {
  input: 'src/modules.js',
  output: {
    file: `${format === 'umd' ? 'dist' : format}/react-md${production ? '.min' : ''}.js`,
    format,
  },
  name: 'ReactMD',
  globals: {
    'react': 'React',
    'react-dom': 'ReactDOM',
  },
  plugins,
  external: [
    'react',
    'react-dom',
  ],
  sourcemap: true,
};
<commit_msg>Updated builds so that the NODE_ENV only gets replaced in umd builds<commit_after>const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const babel = require('rollup-plugin-babel');
const replace = require('rollup-plugin-replace');
const uglify = require('rollup-plugin-uglify');

const format = process.env.BABEL_ENV;
const production = process.env.NODE_ENV === 'production';

const babelPlugins = ['external-helpers'];
if (production) {
  babelPlugins.push('transform-react-remove-prop-types');
}

const plugins = [
  commonjs({
    include: 'node_modules/**',
  }),
  babel({
    babelrc: false,
    exclude: 'node_modules/**',
    presets: [
      ['env', {
        targets: {
          browsers: ['last 2 versions', 'safari > 7'],
        },
        modules: false,
      }],
      'stage-0',
      'react',
    ],
    plugins: babelPlugins,
  }),
  resolve({
    jsnext: true,
    main: true,
    browser: true,
  }),
];

if (format === 'umd') {
  plugins.push(
    replace({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    })
  );
}

if (production) {
  plugins.push(uglify());
}

export default {
  input: 'src/modules.js',
  output: {
    file: `${format === 'umd' ? 'dist' : format}/react-md${production ? '.min' : ''}.js`,
    format,
  },
  name: 'ReactMD',
  globals: {
    'react': 'React',
    'react-dom': 'ReactDOM',
  },
  plugins,
  external: [
    'react',
    'react-dom',
  ],
  sourcemap: true,
};
<|endoftext|>


<commit_before>import {terser} from 'rollup-plugin-terser';
import json from 'rollup-plugin-json';

const jsonPlugin = json({include: 'package.json', preferConst: true});

const umdConf = {
    file: 'dist/es6/dc.js',
    external: ['d3'],
    format: 'umd',
    name: 'dc',
    sourcemap: true,
    globals: {
        d3: 'd3'
    }
};

const umdMinConf = Object.assign({}, umdConf, {file: 'dist/es6/dc.min.js'});

const esmFlat = {
    format: 'esm',
    sourcemap: true,
    file: 'dist/esf/dc.esm.js'
};

const esmFlatMin = Object.assign({}, esmFlat, {file: 'dist/esf/dc.esm.min.js'});

const modulesMap = {
    'index': 'src/index.js',
    'legend': 'src/base/legend.js',
    'html-legend': 'src/base/html-legend.js',
    'bar-chart': 'src/charts/bar-chart.js',
    'box-plot': 'src/charts/box-plot.js',
    'bubble-chart': 'src/charts/bubble-chart.js',
    'bubble-overlay': 'src/charts/bubble-overlay.js',
    'cbox-menu': 'src/charts/cbox-menu.js',
    'composite-chart': 'src/charts/composite-chart.js',
    'data-count': 'src/charts/data-count.js',
    'data-grid': 'src/charts/data-grid.js',
    'data-table': 'src/charts/data-table.js',
    'geo-choropleth-chart': 'src/charts/geo-choropleth-chart.js',
    'heatmap': 'src/charts/heatmap.js',
    'line-chart': 'src/charts/line-chart.js',
    'number-display': 'src/charts/number-display.js',
    'pie-chart': 'src/charts/pie-chart.js',
    'row-chart': 'src/charts/row-chart.js',
    'scatter-plot': 'src/charts/scatter-plot.js',
    'select-menu': 'src/charts/select-menu.js',
    'series-chart': 'src/charts/series-chart.js',
    'sunburst-chart': 'src/charts/sunburst-chart.js',
    'text-filter-widget': 'src/charts/text-filter-widget.js'
};

export default [
    {
        input: 'src/index.js',
        plugins: [
            terser({include: [/^.+\.min\.js$/]}),
            jsonPlugin
        ],
        output: [
            umdConf,
            umdMinConf,
            esmFlat,
            esmFlatMin
        ]
    },
    {
        input: modulesMap,
        plugins: [
            jsonPlugin
        ],
        output: {
            dir: 'dist/esm',
            format: 'esm'
        }
    },
    {
        input: modulesMap,
        plugins: [
            terser(),
            jsonPlugin
        ],
        output: {
            dir: 'dist/esm-min',
            format: 'esm'
        }
    }
];
<commit_msg>Correct error in usage of `external` (for `d3`)<commit_after>import {terser} from 'rollup-plugin-terser';
import json from 'rollup-plugin-json';

const jsonPlugin = json({include: 'package.json', preferConst: true});

const umdConf = {
    file: 'dist/es6/dc.js',
    format: 'umd',
    name: 'dc',
    sourcemap: true,
    globals: {
        d3: 'd3'
    }
};

const umdMinConf = Object.assign({}, umdConf, {file: 'dist/es6/dc.min.js'});

const esmFlat = {
    format: 'esm',
    sourcemap: true,
    file: 'dist/esf/dc.esm.js'
};

const esmFlatMin = Object.assign({}, esmFlat, {file: 'dist/esf/dc.esm.min.js'});

const modulesMap = {
    'index': 'src/index.js',
    'legend': 'src/base/legend.js',
    'html-legend': 'src/base/html-legend.js',
    'bar-chart': 'src/charts/bar-chart.js',
    'box-plot': 'src/charts/box-plot.js',
    'bubble-chart': 'src/charts/bubble-chart.js',
    'bubble-overlay': 'src/charts/bubble-overlay.js',
    'cbox-menu': 'src/charts/cbox-menu.js',
    'composite-chart': 'src/charts/composite-chart.js',
    'data-count': 'src/charts/data-count.js',
    'data-grid': 'src/charts/data-grid.js',
    'data-table': 'src/charts/data-table.js',
    'geo-choropleth-chart': 'src/charts/geo-choropleth-chart.js',
    'heatmap': 'src/charts/heatmap.js',
    'line-chart': 'src/charts/line-chart.js',
    'number-display': 'src/charts/number-display.js',
    'pie-chart': 'src/charts/pie-chart.js',
    'row-chart': 'src/charts/row-chart.js',
    'scatter-plot': 'src/charts/scatter-plot.js',
    'select-menu': 'src/charts/select-menu.js',
    'series-chart': 'src/charts/series-chart.js',
    'sunburst-chart': 'src/charts/sunburst-chart.js',
    'text-filter-widget': 'src/charts/text-filter-widget.js'
};

export default [
    {
        input: 'src/index.js',
        external: ['d3'],
        plugins: [
            terser({include: [/^.+\.min\.js$/]}),
            jsonPlugin
        ],
        output: [
            umdConf,
            umdMinConf,
            esmFlat,
            esmFlatMin
        ]
    },
    {
        input: modulesMap,
        external: ['d3'],
        plugins: [
            jsonPlugin
        ],
        output: {
            dir: 'dist/esm',
            format: 'esm'
        }
    },
    {
        input: modulesMap,
        external: ['d3'],
        plugins: [
            terser(),
            jsonPlugin
        ],
        output: {
            dir: 'dist/esm-min',
            format: 'esm'
        }
    }
];
<|endoftext|>


<commit_before>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    url_parse = require('url').parse,
    stringify = require('qs').stringify,
    multipart = require('./multipart');

var version = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version,
    debug = !!process.env.DEBUG;

exports.version = version;
try { var unzip = require('zlib').unzip } catch(e) { /* zlib not supported */ }

var default_user_agent = "Needle/" + version;
default_user_agent += " (Node.js " + process.version + "; " + process.platform + " " + process.arch + ")";

var node_tls_opts = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized';

var parsers = {
  'application/json': function(data, callback){
    try {
      callback(null, data && JSON.parse(data));
    } catch(e) {
      callback(e, data);
    }
  }
};

try {
  var xml2js = require('xml2js');
  parsers['application/xml'] = function(data, callback){
    var xml_parser = new xml2js.Parser();
    xml_parser.parseString(data, callback);
  };
} catch(e) { /* xml2js not found */ }

var Needle = {

  default_boundary: '--------------------NODENEEDLEHTTPCLIENT',
  default_user_agent: default_user_agent,

  request: function(uri, method, data, options, callback){

    var self = this, post_data = null;
    var callback = (typeof options == 'function') ? options : callback;
    var options = options || {};
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts: {},
      proxy: options.proxy,
      encoding: options.encoding || (options.multipart ? 'binary' : 'utf8'),
      parse_response: options.parse === false ? false : true,
      follow: options.follow === false ? 0 : options.follow || 10, // 10 by default
      timeout: (typeof options.timeout == 'number') ? options.timeout : 10000
    }

    node_tls_opts.split(' ').forEach(function(key){
      if (typeof options[key] != 'undefined'){
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      "User-Agent": options.user_agent || this.default_user_agent,
      "Connection": "close",
      "Accept": "*/*"
    }

    if (options.compressed && typeof unzip != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username && options.password){
      var b = new Buffer([options.username, options.password].join(':'));
      var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
      config.headers[auth_header] = 'Basic ' + b.toString('base64');
    }

    if (data){
      if (options.multipart){

        var boundary = options.boundary || this.default_boundary;
        return multipart.build(data, boundary, function(err, body){

          if (err) throw(err);
          config.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, callback);

        });

      } else {
        post_data = (typeof(data) === "string") ? data : stringify(data);
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        config.headers['Content-Length'] = post_data.length;
      }

    }

    this.send_request(1, method, uri, config, post_data, callback);
  },

  get_request_opts: function(method, uri, config){
    var opts = config.base_opts, proxy = config.proxy;
    var remote = proxy ? url_parse(proxy) : url_parse(uri);

    opts.host = remote.hostname;
    opts.port = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.protocol = remote.protocol;
    opts.path = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method = method;
    opts.headers = config.headers;
    opts.headers["Host"] = proxy ? url_parse(uri).hostname : remote.hostname;

    return opts;
  },

  send_request: function(count, method, uri, config, post_data, callback){

    var self = this, timer,
        request_opts = this.get_request_opts(method, uri, config),
        protocol = request_opts.protocol == 'https:' ? https : http;

    var request = protocol.request(request_opts, function(resp){

      if (timer) clearTimeout(timer);

      if ([301, 302].indexOf(resp.statusCode) != -1 && resp.headers.location){
        if (count <= config.follow)
          return self.send_request(++count, 'GET', resp.headers.location, config, null, callback);
        else if (config.follow > 0)
          return callback(new Error('Redirect loop in ' + resp.headers.location));
      }

      var chunks = [], length = 0,
          compressed = /gzip|deflate/.test(resp.headers['content-encoding']),
          mime = self.parse_content_type(resp.headers['content-type']);

      var response_opts = {
        parse_response: config.parse_response,
        content_type: mime.type,
        charset: mime.charset,
        utf8: mime.charset && mime.charset.match(/utf-?8$/i)
      }

    // response.setEncoding(response_opts.utf8 ? 'utf8' : 'binary');

      resp.on('data', function(chunk){
        chunks.push(chunk);
        length += chunk.length;
      });

      resp.on('end', function(){

        var body = new Buffer(length), pos = 0;
        for (var i = 0, len = chunks.length; i < len; i++){
          chunks[i].copy(body, pos);
          pos += chunks[i].length;
        }

        if (typeof unzip != 'undefined' && compressed)
          unzip(body, function(err, buff){
            self.response_end(response_opts, resp, buff, callback);
          });
        else
          self.response_end(response_opts, resp, body, callback);

      });

    });

    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      if (debug) console.log('Error on request: ' + err.toString());
      if (timer) clearTimeout(timer);
      if (callback) callback(err || new Error("Unkown error on request."));
    });

    if (post_data) request.write(post_data, config.encoding);
    request.end();

  },

  parse_content_type: function(header){
    if (!header || header == '') return {};

    var charset, arr = header.split(';');
    try { charset = arr[1].match(/charset=(.+)/)[1] } catch (e) { /* not found */ }

    return { type: arr[0], charset: charset };
  },

  response_end: function(opts, response, body, callback){

    if (debug) console.log(response.headers);
    if (!callback) return;

    if (opts.parse_response && parsers[opts.content_type]) {
      parsers[opts.content_type](body.toString(), function(err, result){
        callback(err, response, result);
      });
    } else {
      if (!opts.utf8 && opts.charset)
        body = require('iconv-lite').decode(body, opts.charset);

      callback(null, response, body.toString());
    }

  }

}

exports.head = function(uri, options, callback){
  return Needle.request(uri, 'HEAD', null, options, callback);
}

exports.get = function(uri, options, callback){
  return Needle.request(uri, 'GET', null, options, callback);
}

exports.post = function(uri, data, options, callback){
  if (!data || typeof data == 'function') throw('POST request expects data.');
  return Needle.request(uri, 'POST', data, options, callback);
}

exports.put = function(uri, data, options, callback){
  if (!data || typeof data == 'function') throw('PUT request expects data.');
  return Needle.request(uri, 'PUT', data, options, callback);
}

exports.delete = function(uri, data, options, callback){
  return Needle.request(uri, 'DELETE', null, options, callback);
}
<commit_msg>Assume UTF-8 if no charset is found.<commit_after>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    url_parse = require('url').parse,
    stringify = require('qs').stringify,
    multipart = require('./multipart');

var version = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version,
    debug = !!process.env.DEBUG;

exports.version = version;
try { var unzip = require('zlib').unzip } catch(e) { /* zlib not supported */ }

var default_user_agent = "Needle/" + version;
default_user_agent += " (Node.js " + process.version + "; " + process.platform + " " + process.arch + ")";

var node_tls_opts = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized';

var parsers = {
  'application/json': function(data, callback){
    try {
      callback(null, data && JSON.parse(data));
    } catch(e) {
      callback(e, data);
    }
  }
};

try {
  var xml2js = require('xml2js');
  parsers['application/xml'] = function(data, callback){
    var xml_parser = new xml2js.Parser();
    xml_parser.parseString(data, callback);
  };
} catch(e) { /* xml2js not found */ }

var Needle = {

  default_boundary: '--------------------NODENEEDLEHTTPCLIENT',
  default_user_agent: default_user_agent,

  request: function(uri, method, data, options, callback){

    var self = this, post_data = null;
    var callback = (typeof options == 'function') ? options : callback;
    var options = options || {};
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts: {},
      proxy: options.proxy,
      encoding: options.encoding || (options.multipart ? 'binary' : 'utf8'),
      parse_response: options.parse === false ? false : true,
      follow: options.follow === false ? 0 : options.follow || 10, // 10 by default
      timeout: (typeof options.timeout == 'number') ? options.timeout : 10000
    }

    node_tls_opts.split(' ').forEach(function(key){
      if (typeof options[key] != 'undefined'){
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      "User-Agent": options.user_agent || this.default_user_agent,
      "Connection": "close",
      "Accept": "*/*"
    }

    if (options.compressed && typeof unzip != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username && options.password){
      var b = new Buffer([options.username, options.password].join(':'));
      var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
      config.headers[auth_header] = 'Basic ' + b.toString('base64');
    }

    if (data){
      if (options.multipart){

        var boundary = options.boundary || this.default_boundary;
        return multipart.build(data, boundary, function(err, body){

          if (err) throw(err);
          config.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, callback);

        });

      } else {
        post_data = (typeof(data) === "string") ? data : stringify(data);
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        config.headers['Content-Length'] = post_data.length;
      }

    }

    this.send_request(1, method, uri, config, post_data, callback);
  },

  get_request_opts: function(method, uri, config){
    var opts = config.base_opts, proxy = config.proxy;
    var remote = proxy ? url_parse(proxy) : url_parse(uri);

    opts.host = remote.hostname;
    opts.port = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.protocol = remote.protocol;
    opts.path = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method = method;
    opts.headers = config.headers;
    opts.headers["Host"] = proxy ? url_parse(uri).hostname : remote.hostname;

    return opts;
  },

  send_request: function(count, method, uri, config, post_data, callback){

    var self = this, timer,
        request_opts = this.get_request_opts(method, uri, config),
        protocol = request_opts.protocol == 'https:' ? https : http;

    var request = protocol.request(request_opts, function(resp){

      if (timer) clearTimeout(timer);

      if ([301, 302].indexOf(resp.statusCode) != -1 && resp.headers.location){
        if (count <= config.follow)
          return self.send_request(++count, 'GET', resp.headers.location, config, null, callback);
        else if (config.follow > 0)
          return callback(new Error('Redirect loop in ' + resp.headers.location));
      }

      var chunks = [], length = 0,
          compressed = /gzip|deflate/.test(resp.headers['content-encoding']),
          mime = self.parse_content_type(resp.headers['content-type']);

      var response_opts = {
        parse_response: config.parse_response,
        content_type: mime.type,
        charset: mime.charset,
        utf8: mime.charset.match(/utf-?8$/i)
      }

    // response.setEncoding(response_opts.utf8 ? 'utf8' : 'binary');

      resp.on('data', function(chunk){
        chunks.push(chunk);
        length += chunk.length;
      });

      resp.on('end', function(){

        var body = new Buffer(length), pos = 0;
        for (var i = 0, len = chunks.length; i < len; i++){
          chunks[i].copy(body, pos);
          pos += chunks[i].length;
        }

        if (typeof unzip != 'undefined' && compressed)
          unzip(body, function(err, buff){
            self.response_end(response_opts, resp, buff, callback);
          });
        else
          self.response_end(response_opts, resp, body, callback);

      });

    });

    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      if (debug) console.log('Error on request: ' + err.toString());
      if (timer) clearTimeout(timer);
      if (callback) callback(err || new Error("Unkown error on request."));
    });

    if (post_data) request.write(post_data, config.encoding);
    request.end();

  },

  parse_content_type: function(header){
    if (!header || header == '') return {};

    var charset = 'utf-8', arr = header.split(';');
    try { charset = arr[1].match(/charset=(.+)/)[1] } catch (e) { /* not found */ }

    return { type: arr[0], charset: charset };
  },

  response_end: function(opts, response, body, callback){

    if (debug) console.log(response.headers);
    if (!callback) return;

    if (opts.parse_response && parsers[opts.content_type]) {
      parsers[opts.content_type](body.toString(), function(err, result){
        callback(err, response, result);
      });
    } else {
      if (!opts.utf8 && opts.charset)
        body = require('iconv-lite').decode(body, opts.charset);

      callback(null, response, body.toString());
    }

  }

}

exports.head = function(uri, options, callback){
  return Needle.request(uri, 'HEAD', null, options, callback);
}

exports.get = function(uri, options, callback){
  return Needle.request(uri, 'GET', null, options, callback);
}

exports.post = function(uri, data, options, callback){
  if (!data || typeof data == 'function') throw('POST request expects data.');
  return Needle.request(uri, 'POST', data, options, callback);
}

exports.put = function(uri, data, options, callback){
  if (!data || typeof data == 'function') throw('PUT request expects data.');
  return Needle.request(uri, 'PUT', data, options, callback);
}

exports.delete = function(uri, data, options, callback){
  return Needle.request(uri, 'DELETE', null, options, callback);
}
<|endoftext|>


<commit_before>import nodeResolve from 'rollup-plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import replace from 'rollup-plugin-replace';
import { uglify } from 'rollup-plugin-uglify';
import { minify } from 'uglify-js';

const env = process.env.NODE_ENV;
const envHotType = process.env.HOT_TYPE;

const config = {
  input: 'src/common/index.jsx',
  plugins: [
    babel({
      exclude: 'node_modules/**',
    }),
    nodeResolve(),
    replace({
      'hot-alias': envHotType === 'pro' ? 'handsontable-pro' : 'handsontable',
    })
  ],
  external: [
    'react',
    'react-dom'
  ],
};

if (env === 'es' || env === 'cjs') {
  config.output = {
    format: env,
    indent: false,
    file: './' + (env === 'cjs' ? 'commonjs' : env) + '/' + envHotType + '/react-handsontable.js'
  };

  if (env === 'cjs') {
    config.plugins.push(commonjs());
  }

} else if (env === 'umd') {
  config.output = {
    format: 'umd',
    name: 'Handsontable.react.HotTable',
    indent: false,
    file: './dist/' + envHotType + '/react-handsontable.js'
  };

} else if (env === 'min') {
  config.output = {
    format: 'umd',
    name: 'Handsontable.react.HotTable',
    indent: false,
    file: './dist/' + envHotType + '/react-handsontable.min.js'
  };

  config.plugins.push(
    uglify({
      output: {
        comments: /^!/
      },
      compress: {
        pure_getters: true,
        unsafe: true,
        unsafe_comps: true,
        warnings: false
      }
    })
  );
}

if (env === 'umd' || env === 'min') {
  const path = require('path');
  const fs = require('fs');
  const packageBody = require('./src/' + envHotType + '/package.json');

  let licenseBody = fs.readFileSync(path.resolve(__dirname, './LICENSE'), 'utf8');
  licenseBody += '\nVersion: ' + packageBody.version + ' (built at ' + new Date().toString() + ')';

  config.output.banner = '/*!\n' + licenseBody.replace(/^/gm, ' * ') + '\n */';
}

if (envHotType === 'ce') {
  config.external.push('handsontable');

} else if (envHotType === 'pro') {
  config.external.push('handsontable-pro');
}

export default config;
<commit_msg>Move the component’s global variable localtion from Handsontable.react.HotTable.HotTable to Handsontable.react.HotTable. #89 (#90)<commit_after>import nodeResolve from 'rollup-plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import replace from 'rollup-plugin-replace';
import { uglify } from 'rollup-plugin-uglify';
import { minify } from 'uglify-js';

const env = process.env.NODE_ENV;
const envHotType = process.env.HOT_TYPE;

const config = {
  input: 'src/common/index.jsx',
  plugins: [
    babel({
      exclude: 'node_modules/**',
    }),
    nodeResolve(),
    replace({
      'hot-alias': envHotType === 'pro' ? 'handsontable-pro' : 'handsontable',
    })
  ],
  external: [
    'react',
    'react-dom'
  ],
};

if (env === 'es' || env === 'cjs') {
  config.output = {
    format: env,
    indent: false,
    file: './' + (env === 'cjs' ? 'commonjs' : env) + '/' + envHotType + '/react-handsontable.js'
  };

  if (env === 'cjs') {
    config.plugins.push(commonjs());
  }

} else if (env === 'umd') {
  config.output = {
    format: 'umd',
    name: 'Handsontable.react',
    indent: false,
    file: './dist/' + envHotType + '/react-handsontable.js'
  };

} else if (env === 'min') {
  config.output = {
    format: 'umd',
    name: 'Handsontable.react',
    indent: false,
    file: './dist/' + envHotType + '/react-handsontable.min.js'
  };

  config.plugins.push(
    uglify({
      output: {
        comments: /^!/
      },
      compress: {
        pure_getters: true,
        unsafe: true,
        unsafe_comps: true,
        warnings: false
      }
    })
  );
}

if (env === 'umd' || env === 'min') {
  const path = require('path');
  const fs = require('fs');
  const packageBody = require('./src/' + envHotType + '/package.json');

  let licenseBody = fs.readFileSync(path.resolve(__dirname, './LICENSE'), 'utf8');
  licenseBody += '\nVersion: ' + packageBody.version + ' (built at ' + new Date().toString() + ')';

  config.output.banner = '/*!\n' + licenseBody.replace(/^/gm, ' * ') + '\n */';
}

if (envHotType === 'ce') {
  config.external.push('handsontable');

} else if (envHotType === 'pro') {
  config.external.push('handsontable-pro');
}

export default config;
<|endoftext|>


<commit_before>import resolve from "rollup-plugin-node-resolve";
import babel from "rollup-plugin-babel";
import builtins from "rollup-plugin-node-builtins";
import typescript from "rollup-plugin-typescript2";
import commonjs from "rollup-plugin-commonjs";
import cleanup from "rollup-plugin-cleanup";
import json from "rollup-plugin-json";
import pkg from "./package.json";

const external = Object.keys(pkg.dependencies)
  .concat(["crypto"]);
let banner = []

const main = {
  input: "src/lib.ts",
  plugins: [
    typescript({
      check: true,
      clean: true,
      tsconfigOverride: {
        compilerOptions: {
          module: "es6",
          removeComments: true,
        }
      }
    }),
  ],
  external,
  output: [
    {
      banner,
      file: pkg.main,
      format: "cjs",
    },
    {
      banner,
      file: pkg.module,
      format: "es",
    },
  ],
};

//#region Browser
const browserExternals = {
  // "des.js": "des",
  // "elliptic": "elliptic",
};

const browser = [
  {
    input: "src/shim.ts",
    plugins: [
      resolve({
        preferBuiltins: true,
      }),
      json(),
      commonjs(),
      builtins(),
      typescript({
        check: true,
        clean: true,
        tsconfigOverride: {
          compilerOptions: {
            module: "es6",
            removeComments: true,
          }
        }
      }),
      cleanup(),
    ],
    external: Object.keys(browserExternals),
    output: [
      {
        file: pkg.browser,
        format: "es",
        globals: browserExternals,
      }
    ]
  },
  {
    input: pkg.browser,
    plugins: [
      babel({
        babelrc: false,
        runtimeHelpers: true,
        presets: [
          [
            "@babel/env",
            {
              targets: {
                ie: "11",
                chrome: "60",
              },
              useBuiltIns: "entry"
            }
          ]
        ],
        plugins: [
          "@babel/proposal-class-properties",
          "@babel/proposal-object-rest-spread",
        ],
      }),
    ],
    output: [
      {
        file: pkg.browser,
        format: "iife",
        name: "liner",
        intro: "var global = self;"
      },
    ],
  },
];
//#endregion

export default [
  main,
  ...browser,
]<commit_msg>Move elliptic to external dependencies<commit_after>import resolve from "rollup-plugin-node-resolve";
import babel from "rollup-plugin-babel";
import builtins from "rollup-plugin-node-builtins";
import typescript from "rollup-plugin-typescript2";
import commonjs from "rollup-plugin-commonjs";
import cleanup from "rollup-plugin-cleanup";
import json from "rollup-plugin-json";
import pkg from "./package.json";

const external = Object.keys(pkg.dependencies)
  .concat(["crypto"]);
let banner = []

const main = {
  input: "src/lib.ts",
  plugins: [
    typescript({
      check: true,
      clean: true,
      tsconfigOverride: {
        compilerOptions: {
          module: "es6",
          removeComments: true,
        }
      }
    }),
  ],
  external,
  output: [
    {
      banner,
      file: pkg.main,
      format: "cjs",
    },
    {
      banner,
      file: pkg.module,
      format: "es",
    },
  ],
};

//#region Browser
const browserExternals = {
  // "des.js": "des",
  "elliptic": "elliptic",
};

const browser = [
  {
    input: "src/shim.ts",
    plugins: [
      resolve({
        preferBuiltins: true,
      }),
      json(),
      commonjs(),
      builtins(),
      typescript({
        check: true,
        clean: true,
        tsconfigOverride: {
          compilerOptions: {
            module: "es6",
            removeComments: true,
          }
        }
      }),
      cleanup(),
    ],
    external: Object.keys(browserExternals),
    output: [
      {
        file: pkg.browser,
        format: "es",
        globals: browserExternals,
      }
    ]
  },
  {
    input: pkg.browser,
    plugins: [
      babel({
        babelrc: false,
        runtimeHelpers: true,
        presets: [
          [
            "@babel/env",
            {
              targets: {
                ie: "11",
                chrome: "60",
              },
              useBuiltIns: "entry"
            }
          ]
        ],
        plugins: [
          "@babel/proposal-class-properties",
          "@babel/proposal-object-rest-spread",
        ],
      }),
    ],
    output: [
      {
        file: pkg.browser,
        format: "iife",
        name: "liner",
        intro: "var global = self;"
      },
    ],
  },
];
//#endregion

export default [
  main,
  ...browser,
]<|endoftext|>