<commit_before>/* eslint-env node */
"use strict"

const ENVIRONMENT = process.env.NODE_ENV || "development"
const {resolve} = require("path")
const {description, version} = require("./package.json")
const routes = require("./routes.json")
const viewsRoute = routes.views[ENVIRONMENT]
const webpack = require("webpack")
const HtmlWebpackPlugin = require("html-webpack-plugin")
const marked = require("marked")
const autoprefixer = require("autoprefixer")

const toURL = ({hostname, port, protocol}) => `${protocol}://${hostname}${port ? ":" + port : ""}`

const API_BASE = toURL(routes.api[ENVIRONMENT])
const APP_BASE = toURL(routes.app[ENVIRONMENT])
const exclude = /node_modules/

const renderer = new marked.Renderer()
const $ = {}

$.buildDirectory = "site-deploy"

$.devtool = "source-map"

$.entry = {
  site: "./app/index.js"
  // segment: "./app/segment.js" TODO get account key
}

$.markdownLoader = {renderer}

$.output = {
  filename: "[name].js",
  sourceMapFilename: "[name].map"
}

$.plugins = [
  new webpack.NoErrorsPlugin(),
  new webpack.DefinePlugin({
    API_BASE: JSON.stringify(API_BASE),
    APP_BASE: JSON.stringify(APP_BASE),
    VERSION: JSON.stringify(version),
    "process.env.NODE_ENV": JSON.stringify(ENVIRONMENT)
  }),
  new HtmlWebpackPlugin({
    title: "Instant Plugin",
    description,
    template: "app/index.pug"
  })
]

$.resolve = {
  extensions: ["", ".js", ".json"],
  modules: [resolve(__dirname, "app"), "node_modules"]
}

$.postcss = () => [autoprefixer({remove: false, browsers: ["last 2 versions", "ie 10"]})]

const minimizeParam = ENVIRONMENT === "development" ? "-minimize" : "minimize"

$.module = {
  loaders: [
    {test: /\.pug$/, loader: "pug", exclude},
    {test: /\.png|jpe?g|gif$/i, loader: "url?limit=0", exclude},
    {test: /\.js$/, loader: "babel", exclude},
    {test: /\.svg$/, loader: "svg-inline", exclude},
    {test: /\.styl$/, loader: `style!css?${minimizeParam}!postcss!stylus?paths=app`}
  ],
  noParse: /\.min\.js/
}

if (ENVIRONMENT === "development") {
  $.devtool = "eval"

  $.module.preLoaders = [{
    exclude,
    loader: "eslint-loader",
    test: /\.js$/
  }]

  const devServerClient = `webpack-dev-server/client?http://0.0.0.0:${viewsRoute.port}`

  if (Array.isArray($.entry)) {
    $.entry.unshift(devServerClient)
  }
  else {
    $.entry["dev-server-client"] = devServerClient
  }
}

module.exports = $
<commit_msg>Fix output path.<commit_after>/* eslint-env node */
"use strict"

const ENVIRONMENT = process.env.NODE_ENV || "development"
const {resolve} = require("path")
const {description, version} = require("./package.json")
const routes = require("./routes.json")
const viewsRoute = routes.views[ENVIRONMENT]
const webpack = require("webpack")
const HtmlWebpackPlugin = require("html-webpack-plugin")
const marked = require("marked")
const autoprefixer = require("autoprefixer")

const toURL = ({hostname, port, protocol}) => `${protocol}://${hostname}${port ? ":" + port : ""}`

const API_BASE = toURL(routes.api[ENVIRONMENT])
const APP_BASE = toURL(routes.app[ENVIRONMENT])
const exclude = /node_modules/

const renderer = new marked.Renderer()
const $ = {}

$.devtool = "source-map"

$.entry = {
  site: "./app/index.js"
  // segment: "./app/segment.js" TODO get account key
}

$.markdownLoader = {renderer}

$.output = {
  path: __dirname + "/site-deploy",
  filename: "[name].js",
  sourceMapFilename: "[name].map"
}

$.plugins = [
  new webpack.NoErrorsPlugin(),
  new webpack.DefinePlugin({
    API_BASE: JSON.stringify(API_BASE),
    APP_BASE: JSON.stringify(APP_BASE),
    VERSION: JSON.stringify(version),
    "process.env.NODE_ENV": JSON.stringify(ENVIRONMENT)
  }),
  new HtmlWebpackPlugin({
    title: "Instant Plugin",
    description,
    template: "app/index.pug"
  })
]

$.resolve = {
  extensions: ["", ".js", ".json"],
  modules: [resolve(__dirname, "app"), "node_modules"]
}

$.postcss = () => [autoprefixer({remove: false, browsers: ["last 2 versions", "ie 10"]})]

const minimizeParam = ENVIRONMENT === "development" ? "-minimize" : "minimize"

$.module = {
  loaders: [
    {test: /\.pug$/, loader: "pug", exclude},
    {test: /\.png|jpe?g|gif$/i, loader: "url?limit=0", exclude},
    {test: /\.js$/, loader: "babel", exclude},
    {test: /\.svg$/, loader: "svg-inline", exclude},
    {test: /\.styl$/, loader: `style!css?${minimizeParam}!postcss!stylus?paths=app`}
  ],
  noParse: /\.min\.js/
}

if (ENVIRONMENT === "development") {
  $.devtool = "eval"

  $.module.preLoaders = [{
    exclude,
    loader: "eslint-loader",
    test: /\.js$/
  }]

  const devServerClient = `webpack-dev-server/client?http://0.0.0.0:${viewsRoute.port}`

  if (Array.isArray($.entry)) {
    $.entry.unshift(devServerClient)
  }
  else {
    $.entry["dev-server-client"] = devServerClient
  }
}

module.exports = $
<|endoftext|>


<commit_before>var webpack = require('webpack')
var path = require('path')
module.exports = {
  context: __dirname,
  entry: './browser',
  output: {
    path: path.join(__dirname, '/browser-dist'),
    filename: 'contentful.js',
    library: 'contentful'
  },
  module: {
    loaders: [
      {
        test: /\.js?$/,
        exclude: /(node_modules|bower_components|dist)/,
        loader: 'babel'
      },
      {
        test: /\.json?$/,
        loader: 'json'
      }
    ]
  },
  plugins: [
    new webpack.NormalModuleReplacementPlugin(/\.\/vendor-node\/axios/g, './vendor-browser/axios.js')
  ]
}
<commit_msg>fix: Path for browser-dist folder<commit_after>var webpack = require('webpack')
var path = require('path')
module.exports = {
  context: __dirname,
  entry: './browser',
  output: {
    path: path.join(__dirname, 'browser-dist'),
    filename: 'contentful.js',
    library: 'contentful'
  },
  module: {
    loaders: [
      {
        test: /\.js?$/,
        exclude: /(node_modules|bower_components|dist)/,
        loader: 'babel'
      },
      {
        test: /\.json?$/,
        loader: 'json'
      }
    ]
  },
  plugins: [
    new webpack.NormalModuleReplacementPlugin(/\.\/vendor-node\/axios/g, './vendor-browser/axios.js')
  ]
}
<|endoftext|>


<commit_before>
function PatchFile(patchset, name)
{
    this.name = name || "";
    this.language = PatchFile.computeLanguage(name);
    this.containsEmbeddedLanguages = PatchFile.MIXED_LANGUAGES[this.language];
    this.status = "";
    this.chunks = 0;
    this.missingBaseFile = false;
    this.propertyChanges = "";
    this.added = 0;
    this.removed = 0;
    this.id = 0;
    this.patchset = patchset || null; // PatchSet
    this.isBinary = false;
    this.messages = {}; // Map<line number, Array<PatchFileMessage>>
    this.messageCount = 0;
    this.draftCount = 0;
}

PatchFile.REVIEW_URL = "/{1}/diff/{2}/{3}";
PatchFile.DIFF_URL = "/download/issue{1}_{2}_{3}.diff";
PatchFile.CONTEXT_URL = "/{1}/diff_skipped_lines/{2}/{3}/{4}/{5}/a/2000";
PatchFile.COMMENT_URL = "/inline_draft";
PatchFile.IMAGE_URL = "/{1}/image/{2}/{3}/{4}";

PatchFile.MIXED_LANGUAGES = {
    "html": true,
    "svg": true,
    "xhtml": true,
    "xml": true,
};

PatchFile.computeLanguage = function(name)
{
    if (!name)
        return "";
    if (name.endsWith(/\.(cpp|h)$/))
        return "cpp";
    if (name.endsWith(/\.(html|xhtml)$/))
        return "html";
    if (name.endsWith(".js"))
        return "javascript";
    if (name.endsWith(".css"))
        return "css";
    if (name.endsWith(/\.(xml|svg)$/))
        return "xml";
    if (name.endsWith(/\.(pl|pm|cgi)$/))
        return "perl";
    if (name.endsWith(".py"))
        return "python";
    if (name.endsWith(".rb"))
        return "ruby";
    if (name.endsWith(".mm"))
        return "objectivec";
    if (name.endsWith(".json"))
        return "json";
    // FIXME: We should create a proper language definition for idl. For now we
    // use ActionScript since they're actually quite similar.
    if (name.endsWith(".idl"))
        return "actionscript";
    return "";
};

PatchFile.prototype.shouldResetEmbeddedLanguage = function(language, text)
{
    if (!this.containsEmbeddedLanguages)
        return false;
    if (language == "javascript" && text.startsWith("<\/script"))
        return true;
    if (language == "css" && text.startsWith("<\/style"))
        return true;
    return false;
};

// FIXME: This isn't perfect, you can easily confuse it with multiple script
// or style tags on the same line. It's good enough for most reviews though.
PatchFile.prototype.selectEmbeddedLanguage = function(text)
{
    if (!this.containsEmbeddedLanguages)
        return this.language;
    if (text.startsWith("<script") && !text.contains("<\/script"))
        return "javascript";
    if (text.startsWith("<style") && !text.contains("<\/style"))
        return "css";
    return this.language;
};

PatchFile.prototype.addMessage = function(message)
{
    if (!this.messages[message.line])
        this.messages[message.line] = [];
    this.messages[message.line].push(message);
    if (message.draft)
        this.draftCount++;
    else
        this.messageCount++;
};

PatchFile.prototype.removeMessage = function(message)
{
    var messages = this.messages[message.line];
    if (!messages || !messages.find(message))
        return;
    messages.remove(message);
    if (message.draft)
        this.draftCount--;
    else
        this.messageCount--;
};

PatchFile.prototype.parseData = function(data)
{
    this.status = data.status || "";
    this.chunks = data.num_chunks || 0;
    this.missingBaseFile = data.no_base_file || false;
    this.propertyChanges = data.property_changes || "";
    this.added = Math.max(0, data.num_added || 0);
    this.removed = Math.max(0, data.num_removed || 0);
    this.id = data.id || 0;
    this.isBinary = data.is_binary || false;

    var self = this;
    (data.messages || []).forEach(function(messageData) {
        var message = new PatchFileMessage();
        message.parseData(messageData);
        self.addMessage(message);
    });

    Object.each(this.messages, function(line, messages) {
        messages.sort(function(messageA, messageB) {
            return messageA.date - messageB.date;
        });
    });
};

PatchFile.prototype.getReviewUrl = function()
{
    // We don't uri encode the name since it's part of the url path.
    return PatchFile.REVIEW_URL.assign(
        encodeURIComponent(this.patchset.issue.id),
        encodeURIComponent(this.patchset.id),
        this.name);
};

PatchFile.prototype.getDiffUrl = function()
{
    return PatchFile.DIFF_URL.assign(
        encodeURIComponent(this.patchset.issue.id),
        encodeURIComponent(this.patchset.id),
        encodeURIComponent(this.id));
};

PatchFile.prototype.getOldImageUrl = function()
{
    return PatchFile.IMAGE_URL.assign(
        encodeURIComponent(this.patchset.issue.id),
        encodeURIComponent(this.patchset.id),
        encodeURIComponent(this.id),
        0);
};

PatchFile.prototype.getNewImageUrl = function()
{
    return PatchFile.IMAGE_URL.assign(
        encodeURIComponent(this.patchset.issue.id),
        encodeURIComponent(this.patchset.id),
        encodeURIComponent(this.id),
        1);
};

PatchFile.prototype.getContextUrl = function(start, end)
{
    return PatchFile.CONTEXT_URL.assign(
        encodeURIComponent(this.patchset.issue.id),
        encodeURIComponent(this.patchset.id),
        encodeURIComponent(this.id),
        encodeURIComponent(start),
        encodeURIComponent(end));
};

PatchFile.prototype.saveDraft = function(message, newText)
{
    return this.createDraftData(message).then(function(data) {
        data.text = newText;
        return sendFormData(PatchFile.COMMENT_URL, data).then(function(xhr) {
            var id = PatchFileMessage.findDraftMessageId(xhr.response);
            if (!id)
                throw new Error("Cannot save draft");
            // This isn't really the correct date, but it's good enough to just
            // approximate that it was saved right now.
            message.date = Date.utc.create();
            message.messageId = id;
            message.text = newText;
            return true;
        });
    });
};

PatchFile.prototype.discardDraft = function(message)
{
    return this.createDraftData(message).then(function(data) {
        data.old_text = message.text;
        data.text = "";
        data.file = "";
        return sendFormData(PatchFile.COMMENT_URL, data).then(function() {
            return true;
        });
    });
};

PatchFile.prototype.createDraftData = function(message)
{
    return Promise.resolve({
        snapshot: message.left ? "old" : "new",
        lineno: message.line,
        side: message.left ? "a" : "b",
        issue: this.patchset.issue.id,
        patchset: this.patchset.id,
        patch: this.id,
        text: message.text,
        message_id: message.messageId,
    });
};

PatchFile.prototype.loadDiff = function()
{
    var file = this;
    return loadText(this.getDiffUrl()).then(function(text) {
        return file.parseDiff(text);
    });
};

PatchFile.prototype.parseDiff = function(text)
{
    var parser = new DiffParser(text);
    var result = parser.parse();
    if (!result || !result[0] || result[0].name != this.name)
        throw new Error("No diff available");
    var diff = result[0];
    if (!diff.external || diff.isImage)
        return diff;
    return this.loadContext(0, Number.MAX_SAFE_INTEGER).then(function(lines) {
        diff.groups = [lines];
        return diff;
    });
};

PatchFile.prototype.loadContext = function(start, end)
{
    var file = this;
    return loadJSON(this.getContextUrl(start, end)).then(function(data) {
        return file.parseContext(data);
    });
};

PatchFile.prototype.parseContext = function(data)
{
    var lines = [];
    for (var i = 0; i < data.length; i += 2) {
        var newLine = PatchFile.parseContextLine(data[i][1][1][1]);
        var oldLine = PatchFile.parseContextLine(data[i][1][0][1]);
        // FIXME: Rietveld will respond with mysterious lines sometimes, for now
        // we harden the code to skip them instead of throwing errors.
        if (!newLine || !oldLine)
            continue;
        lines.push({
            type: "both",
            beforeNumber: oldLine.lineNumber,
            afterNumber: newLine.lineNumber,
            contextLinesStart: 0,
            contextLinesEnd: 0,
            context: false,
            text: newLine.text,
        });
    }
    return lines;
};

PatchFile.parseContextLine = function(text)
{
    if (!text)
        return null;
    var numberStart = 0;
    while (text[numberStart] == " " && numberStart < text.length)
        ++numberStart;
    var numberEnd = numberStart;
    while (text[numberEnd] != " " && numberEnd < text.length)
        ++numberEnd;
    return {
        lineNumber: parseInt(text.substring(numberStart, numberEnd), 10),
        text: text.from(numberEnd + 1),
    };
};
<commit_msg>Get rid of PatchFile#getReviewUrl()<commit_after>
function PatchFile(patchset, name)
{
    this.name = name || "";
    this.language = PatchFile.computeLanguage(name);
    this.containsEmbeddedLanguages = PatchFile.MIXED_LANGUAGES[this.language];
    this.status = "";
    this.chunks = 0;
    this.missingBaseFile = false;
    this.propertyChanges = "";
    this.added = 0;
    this.removed = 0;
    this.id = 0;
    this.patchset = patchset || null; // PatchSet
    this.isBinary = false;
    this.messages = {}; // Map<line number, Array<PatchFileMessage>>
    this.messageCount = 0;
    this.draftCount = 0;
}

PatchFile.DIFF_URL = "/download/issue{1}_{2}_{3}.diff";
PatchFile.CONTEXT_URL = "/{1}/diff_skipped_lines/{2}/{3}/{4}/{5}/a/2000";
PatchFile.COMMENT_URL = "/inline_draft";
PatchFile.IMAGE_URL = "/{1}/image/{2}/{3}/{4}";

PatchFile.MIXED_LANGUAGES = {
    "html": true,
    "svg": true,
    "xhtml": true,
    "xml": true,
};

PatchFile.computeLanguage = function(name)
{
    if (!name)
        return "";
    if (name.endsWith(/\.(cpp|h)$/))
        return "cpp";
    if (name.endsWith(/\.(html|xhtml)$/))
        return "html";
    if (name.endsWith(".js"))
        return "javascript";
    if (name.endsWith(".css"))
        return "css";
    if (name.endsWith(/\.(xml|svg)$/))
        return "xml";
    if (name.endsWith(/\.(pl|pm|cgi)$/))
        return "perl";
    if (name.endsWith(".py"))
        return "python";
    if (name.endsWith(".rb"))
        return "ruby";
    if (name.endsWith(".mm"))
        return "objectivec";
    if (name.endsWith(".json"))
        return "json";
    // FIXME: We should create a proper language definition for idl. For now we
    // use ActionScript since they're actually quite similar.
    if (name.endsWith(".idl"))
        return "actionscript";
    return "";
};

PatchFile.prototype.shouldResetEmbeddedLanguage = function(language, text)
{
    if (!this.containsEmbeddedLanguages)
        return false;
    if (language == "javascript" && text.startsWith("<\/script"))
        return true;
    if (language == "css" && text.startsWith("<\/style"))
        return true;
    return false;
};

// FIXME: This isn't perfect, you can easily confuse it with multiple script
// or style tags on the same line. It's good enough for most reviews though.
PatchFile.prototype.selectEmbeddedLanguage = function(text)
{
    if (!this.containsEmbeddedLanguages)
        return this.language;
    if (text.startsWith("<script") && !text.contains("<\/script"))
        return "javascript";
    if (text.startsWith("<style") && !text.contains("<\/style"))
        return "css";
    return this.language;
};

PatchFile.prototype.addMessage = function(message)
{
    if (!this.messages[message.line])
        this.messages[message.line] = [];
    this.messages[message.line].push(message);
    if (message.draft)
        this.draftCount++;
    else
        this.messageCount++;
};

PatchFile.prototype.removeMessage = function(message)
{
    var messages = this.messages[message.line];
    if (!messages || !messages.find(message))
        return;
    messages.remove(message);
    if (message.draft)
        this.draftCount--;
    else
        this.messageCount--;
};

PatchFile.prototype.parseData = function(data)
{
    this.status = data.status || "";
    this.chunks = data.num_chunks || 0;
    this.missingBaseFile = data.no_base_file || false;
    this.propertyChanges = data.property_changes || "";
    this.added = Math.max(0, data.num_added || 0);
    this.removed = Math.max(0, data.num_removed || 0);
    this.id = data.id || 0;
    this.isBinary = data.is_binary || false;

    var self = this;
    (data.messages || []).forEach(function(messageData) {
        var message = new PatchFileMessage();
        message.parseData(messageData);
        self.addMessage(message);
    });

    Object.each(this.messages, function(line, messages) {
        messages.sort(function(messageA, messageB) {
            return messageA.date - messageB.date;
        });
    });
};

PatchFile.prototype.getDiffUrl = function()
{
    return PatchFile.DIFF_URL.assign(
        encodeURIComponent(this.patchset.issue.id),
        encodeURIComponent(this.patchset.id),
        encodeURIComponent(this.id));
};

PatchFile.prototype.getOldImageUrl = function()
{
    return PatchFile.IMAGE_URL.assign(
        encodeURIComponent(this.patchset.issue.id),
        encodeURIComponent(this.patchset.id),
        encodeURIComponent(this.id),
        0);
};

PatchFile.prototype.getNewImageUrl = function()
{
    return PatchFile.IMAGE_URL.assign(
        encodeURIComponent(this.patchset.issue.id),
        encodeURIComponent(this.patchset.id),
        encodeURIComponent(this.id),
        1);
};

PatchFile.prototype.getContextUrl = function(start, end)
{
    return PatchFile.CONTEXT_URL.assign(
        encodeURIComponent(this.patchset.issue.id),
        encodeURIComponent(this.patchset.id),
        encodeURIComponent(this.id),
        encodeURIComponent(start),
        encodeURIComponent(end));
};

PatchFile.prototype.saveDraft = function(message, newText)
{
    return this.createDraftData(message).then(function(data) {
        data.text = newText;
        return sendFormData(PatchFile.COMMENT_URL, data).then(function(xhr) {
            var id = PatchFileMessage.findDraftMessageId(xhr.response);
            if (!id)
                throw new Error("Cannot save draft");
            // This isn't really the correct date, but it's good enough to just
            // approximate that it was saved right now.
            message.date = Date.utc.create();
            message.messageId = id;
            message.text = newText;
            return true;
        });
    });
};

PatchFile.prototype.discardDraft = function(message)
{
    return this.createDraftData(message).then(function(data) {
        data.old_text = message.text;
        data.text = "";
        data.file = "";
        return sendFormData(PatchFile.COMMENT_URL, data).then(function() {
            return true;
        });
    });
};

PatchFile.prototype.createDraftData = function(message)
{
    return Promise.resolve({
        snapshot: message.left ? "old" : "new",
        lineno: message.line,
        side: message.left ? "a" : "b",
        issue: this.patchset.issue.id,
        patchset: this.patchset.id,
        patch: this.id,
        text: message.text,
        message_id: message.messageId,
    });
};

PatchFile.prototype.loadDiff = function()
{
    var file = this;
    return loadText(this.getDiffUrl()).then(function(text) {
        return file.parseDiff(text);
    });
};

PatchFile.prototype.parseDiff = function(text)
{
    var parser = new DiffParser(text);
    var result = parser.parse();
    if (!result || !result[0] || result[0].name != this.name)
        throw new Error("No diff available");
    var diff = result[0];
    if (!diff.external || diff.isImage)
        return diff;
    return this.loadContext(0, Number.MAX_SAFE_INTEGER).then(function(lines) {
        diff.groups = [lines];
        return diff;
    });
};

PatchFile.prototype.loadContext = function(start, end)
{
    var file = this;
    return loadJSON(this.getContextUrl(start, end)).then(function(data) {
        return file.parseContext(data);
    });
};

PatchFile.prototype.parseContext = function(data)
{
    var lines = [];
    for (var i = 0; i < data.length; i += 2) {
        var newLine = PatchFile.parseContextLine(data[i][1][1][1]);
        var oldLine = PatchFile.parseContextLine(data[i][1][0][1]);
        // FIXME: Rietveld will respond with mysterious lines sometimes, for now
        // we harden the code to skip them instead of throwing errors.
        if (!newLine || !oldLine)
            continue;
        lines.push({
            type: "both",
            beforeNumber: oldLine.lineNumber,
            afterNumber: newLine.lineNumber,
            contextLinesStart: 0,
            contextLinesEnd: 0,
            context: false,
            text: newLine.text,
        });
    }
    return lines;
};

PatchFile.parseContextLine = function(text)
{
    if (!text)
        return null;
    var numberStart = 0;
    while (text[numberStart] == " " && numberStart < text.length)
        ++numberStart;
    var numberEnd = numberStart;
    while (text[numberEnd] != " " && numberEnd < text.length)
        ++numberEnd;
    return {
        lineNumber: parseInt(text.substring(numberStart, numberEnd), 10),
        text: text.from(numberEnd + 1),
    };
};
<|endoftext|>


<commit_before>var webpack = require('webpack');
var UglifyJsPlugin = require('uglifyjs-webpack-plugin');

var pkg = require('./package.json');
var year = new Date().getFullYear();
var banner = '\
\n\
 SIP version ' + pkg.version + '\n\
 Copyright (c) 2014-' + year + ' Junction Networks, Inc <http://www.onsip.com>\n\
 Homepage: https://sipjs.com\n\
 License: https://sipjs.com/license/\n\
\n\
\n\
 ~~~SIP.js contains substantial portions of JsSIP under the following license~~~\n\
 Homepage: http://jssip.net\n\
 Copyright (c) 2012-2013 José Luis Millán - Versatica <http://www.versatica.com>\n\
\n\
 Permission is hereby granted, free of charge, to any person obtaining\n\
 a copy of this software and associated documentation files (the\n\
 "Software"), to deal in the Software without restriction, including\n\
 without limitation the rights to use, copy, modify, merge, publish,\n\
 distribute, sublicense, and/or sell copies of the Software, and to\n\
 permit persons to whom the Software is furnished to do so, subject to\n\
 the following conditions:\n\
\n\
 The above copyright notice and this permission notice shall be\n\
 included in all copies or substantial portions of the Software.\n\
\n\
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\n\
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n\
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n\
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n\
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\
\n\
 ~~~ end JsSIP license ~~~\n\
\n\n\n';

module.exports = function (env) {
  var mode = env.buildType === 'prod' ? 'production' : 'development';

  var entry = {};
  entry['sip' + (env.buildType === 'prod' ? '.min' : '')] = __dirname + '/src/index.js';

  return {
    mode: mode,
    entry: entry,
    output: {
      path: __dirname + '/dist',
      filename: '[name].js',
      library: 'SIP',
      libraryTarget: 'umd',
      globalObject: 'this'
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: "babel-loader",
          options: {
            presets: ['env']
          }
        },
        {
          test: /\.pegjs$/,
          loader: 'pegjs-loader',
          options: {
            'optimize': 'size',
            'allowedStartRules':
            [
              "Contact",
              "Name_Addr_Header",
              "Record_Route",
              "Request_Response",
              "SIP_URI",
              "Subscription_State",
              "Supported",
              "Require",
              "Via",
              "absoluteURI",
              "Call_ID",
              "Content_Disposition",
              "Content_Length",
              "Content_Type",
              "CSeq",
              "displayName",
              "Event",
              "From",
              "host",
              "Max_Forwards",
              "Min_SE",
              "Proxy_Authenticate",
              "quoted_string",
              "Refer_To",
              "Replaces",
              "Session_Expires",
              "stun_URI",
              "To",
              "turn_URI",
              "uuid",
              "WWW_Authenticate",
              "challenge",
              "sipfrag",
              "Referred_By"
            ]
          }
        }
      ]
    },
    optimization: {
      minimizer: [
        new UglifyJsPlugin({
          uglifyOptions: {
            output: {
              ascii_only: true
            }
          }
        })
      ]
    },
    plugins: [
      new webpack.BannerPlugin({
        banner: banner
      })
    ]
  };
}
<commit_msg>switch unminified build from 'development' mode to 'none' mode to match previous unminified builds<commit_after>var webpack = require('webpack');
var UglifyJsPlugin = require('uglifyjs-webpack-plugin');

var pkg = require('./package.json');
var year = new Date().getFullYear();
var banner = '\
\n\
 SIP version ' + pkg.version + '\n\
 Copyright (c) 2014-' + year + ' Junction Networks, Inc <http://www.onsip.com>\n\
 Homepage: https://sipjs.com\n\
 License: https://sipjs.com/license/\n\
\n\
\n\
 ~~~SIP.js contains substantial portions of JsSIP under the following license~~~\n\
 Homepage: http://jssip.net\n\
 Copyright (c) 2012-2013 José Luis Millán - Versatica <http://www.versatica.com>\n\
\n\
 Permission is hereby granted, free of charge, to any person obtaining\n\
 a copy of this software and associated documentation files (the\n\
 "Software"), to deal in the Software without restriction, including\n\
 without limitation the rights to use, copy, modify, merge, publish,\n\
 distribute, sublicense, and/or sell copies of the Software, and to\n\
 permit persons to whom the Software is furnished to do so, subject to\n\
 the following conditions:\n\
\n\
 The above copyright notice and this permission notice shall be\n\
 included in all copies or substantial portions of the Software.\n\
\n\
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\n\
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n\
 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n\
 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n\
 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\
\n\
 ~~~ end JsSIP license ~~~\n\
\n\n\n';

module.exports = function (env) {
  var mode = env.buildType === 'prod' ? 'production' : 'none';

  var entry = {};
  entry['sip' + (env.buildType === 'prod' ? '.min' : '')] = __dirname + '/src/index.js';

  return {
    mode: mode,
    entry: entry,
    output: {
      path: __dirname + '/dist',
      filename: '[name].js',
      library: 'SIP',
      libraryTarget: 'umd',
      globalObject: 'this'
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: "babel-loader",
          options: {
            presets: ['env']
          }
        },
        {
          test: /\.pegjs$/,
          loader: 'pegjs-loader',
          options: {
            'optimize': 'size',
            'allowedStartRules':
            [
              "Contact",
              "Name_Addr_Header",
              "Record_Route",
              "Request_Response",
              "SIP_URI",
              "Subscription_State",
              "Supported",
              "Require",
              "Via",
              "absoluteURI",
              "Call_ID",
              "Content_Disposition",
              "Content_Length",
              "Content_Type",
              "CSeq",
              "displayName",
              "Event",
              "From",
              "host",
              "Max_Forwards",
              "Min_SE",
              "Proxy_Authenticate",
              "quoted_string",
              "Refer_To",
              "Replaces",
              "Session_Expires",
              "stun_URI",
              "To",
              "turn_URI",
              "uuid",
              "WWW_Authenticate",
              "challenge",
              "sipfrag",
              "Referred_By"
            ]
          }
        }
      ]
    },
    optimization: {
      minimizer: [
        new UglifyJsPlugin({
          uglifyOptions: {
            output: {
              ascii_only: true
            }
          }
        })
      ]
    },
    plugins: [
      new webpack.BannerPlugin({
        banner: banner
      })
    ]
  };
}
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        "bundle": "./src/vector/index.js",

        // We ship olm.js as a separate lump of javascript. This makes it get
        // loaded via a separate <script/> tag in index.html (which loads it
        // into the browser global `Olm`), and define it as an external below.
        //
        // (we should probably make js-sdk load it asynchronously at some
        // point, so that it doesn't block the pageload, but that is a separate
        // problem)
        "olm": "olm/olm.js",
    },
    module: {
        preLoaders: [
            { test: /\.js$/, loader: "source-map-loader" }
        ],
        loaders: [
            { test: /\.json$/, loader: "json" },
            { test: /\.js$/, loader: "babel", include: path.resolve('./src') },
            // css-raw-loader loads CSS but doesn't try to treat url()s as require()s
            { test: /\.css$/, loader: ExtractTextPlugin.extract("css-raw-loader") },
        ],
        noParse: [
            // don't parse the languages within highlight.js. They cause stack
            // overflows (https://github.com/webpack/webpack/issues/1721), and
            // there is no need for webpack to parse them - they can just be
            // included as-is.
            /highlight\.js\/lib\/languages/,

            // olm takes ages for webpack to process, and it's already heavily
            // optimised, so there is little to gain by us uglifying it.
            /olm\/(javascript\/)?olm\.js$/,
        ],
    },
    output: {
        path: path.join(__dirname, "webapp"),
        filename: "[name].[chunkhash].js",
        devtoolModuleFilenameTemplate: function(info) {
            // Reading input source maps gives only relative paths here for
            // everything. Until I figure out how to fix this, this is a
            // workaround.
            // We use the relative resource path with any '../'s on the front
            // removed which gives a tree with matrix-react-sdk and vector
            // trees smashed together, but this fixes everything being under
            // various levels of '.' and '..'
            // Also, sometimes the resource path is absolute.
            return path.relative(process.cwd(), info.resourcePath).replace(/^[\/\.]*/, '');
        }
    },
    resolve: {
        alias: {
            // alias any requires to the react module to the one in our path, otherwise
            // we tend to get the react source included twice when using npm link.
            react: path.resolve('./node_modules/react'),
            "react-addons-perf": path.resolve('./node_modules/react-addons-perf'),

            // same goes for js-sdk
            "matrix-js-sdk": path.resolve('./node_modules/matrix-js-sdk'),
        },
    },
    externals: {
        "olm": "Olm",
        // Don't try to bundle electron: leave it as a commonjs dependency
        // (the 'commonjs' here means it will output a 'require')
        "electron": "commonjs electron",
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify(process.env.NODE_ENV)
            }
        }),

        new ExtractTextPlugin(
            "[name].[contenthash].css",
            {
                allChunks: true
            }
        ),

        new HtmlWebpackPlugin({
            template: './src/vector/index.html',

            // we inject the links ourselves via the template, because
            // HtmlWebpackPlugin wants to put the script tags either at the
            // bottom of <head> or the bottom of <body>, and I'm a bit scared
            // about moving them.
            inject: false,
        }),
    ],
    devtool: 'source-map',

    // configuration for the webpack-dev-server
    devServer: {
        // serve unwebpacked assets from webapp.
        contentBase: './webapp',
    },
};

// olm is an optional dependency. Ignore it if it's not installed, to avoid a
// scary-looking error.
try {
    require('olm');
} catch (e) {
    console.log("Olm is not installed; not shipping it");
    delete(module.exports.entry["olm"]);
}
<commit_msg>Make sure we only pack one copy of react-dom (#2603)<commit_after>var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        "bundle": "./src/vector/index.js",

        // We ship olm.js as a separate lump of javascript. This makes it get
        // loaded via a separate <script/> tag in index.html (which loads it
        // into the browser global `Olm`), and define it as an external below.
        //
        // (we should probably make js-sdk load it asynchronously at some
        // point, so that it doesn't block the pageload, but that is a separate
        // problem)
        "olm": "olm/olm.js",
    },
    module: {
        preLoaders: [
            { test: /\.js$/, loader: "source-map-loader" }
        ],
        loaders: [
            { test: /\.json$/, loader: "json" },
            { test: /\.js$/, loader: "babel", include: path.resolve('./src') },
            // css-raw-loader loads CSS but doesn't try to treat url()s as require()s
            { test: /\.css$/, loader: ExtractTextPlugin.extract("css-raw-loader") },
        ],
        noParse: [
            // don't parse the languages within highlight.js. They cause stack
            // overflows (https://github.com/webpack/webpack/issues/1721), and
            // there is no need for webpack to parse them - they can just be
            // included as-is.
            /highlight\.js\/lib\/languages/,

            // olm takes ages for webpack to process, and it's already heavily
            // optimised, so there is little to gain by us uglifying it.
            /olm\/(javascript\/)?olm\.js$/,
        ],
    },
    output: {
        path: path.join(__dirname, "webapp"),
        filename: "[name].[chunkhash].js",
        devtoolModuleFilenameTemplate: function(info) {
            // Reading input source maps gives only relative paths here for
            // everything. Until I figure out how to fix this, this is a
            // workaround.
            // We use the relative resource path with any '../'s on the front
            // removed which gives a tree with matrix-react-sdk and vector
            // trees smashed together, but this fixes everything being under
            // various levels of '.' and '..'
            // Also, sometimes the resource path is absolute.
            return path.relative(process.cwd(), info.resourcePath).replace(/^[\/\.]*/, '');
        }
    },
    resolve: {
        alias: {
            // alias any requires to the react module to the one in our path, otherwise
            // we tend to get the react source included twice when using npm link.
            "react": path.resolve('./node_modules/react'),
            "react-dom": path.resolve('./node_modules/react-dom'),
            "react-addons-perf": path.resolve('./node_modules/react-addons-perf'),

            // same goes for js-sdk
            "matrix-js-sdk": path.resolve('./node_modules/matrix-js-sdk'),
        },
    },
    externals: {
        "olm": "Olm",
        // Don't try to bundle electron: leave it as a commonjs dependency
        // (the 'commonjs' here means it will output a 'require')
        "electron": "commonjs electron",
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify(process.env.NODE_ENV)
            }
        }),

        new ExtractTextPlugin(
            "[name].[contenthash].css",
            {
                allChunks: true
            }
        ),

        new HtmlWebpackPlugin({
            template: './src/vector/index.html',

            // we inject the links ourselves via the template, because
            // HtmlWebpackPlugin wants to put the script tags either at the
            // bottom of <head> or the bottom of <body>, and I'm a bit scared
            // about moving them.
            inject: false,
        }),
    ],
    devtool: 'source-map',

    // configuration for the webpack-dev-server
    devServer: {
        // serve unwebpacked assets from webapp.
        contentBase: './webapp',
    },
};

// olm is an optional dependency. Ignore it if it's not installed, to avoid a
// scary-looking error.
try {
    require('olm');
} catch (e) {
    console.log("Olm is not installed; not shipping it");
    delete(module.exports.entry["olm"]);
}
<|endoftext|>


<commit_before>const webpack = require('webpack');

// 将babel-loader的配置独立出来, 因为webpack的限制: http://stackoverflow.com/questions/33117136/how-to-add-a-query-to-a-webpack-loader-with-multiple-loaders
const babelLoaderConfig = {
  presets: ['latest', 'stage-0', 'react'],  // 开启ES6、部分ES7、react特性, preset相当于预置的插件集合
  plugins: [['import', {libraryName: 'antd', style: true}]],  // antd模块化加载, https://github.com/ant-design/babel-plugin-import
  cacheDirectory: true,
};

module.exports = {
  devtool: 'eval-source-map',

  entry: [
    'webpack-dev-server/client?http://0.0.0.0:8080', // WebpackDevServer host and port
    'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
    'babel-polyfill',  // 可以使用完整的ES6特性, 大概增加100KB
    './src/index.js',  // 编译的入口
  ],

  output: {  // 输出的目录和文件名
    path: __dirname + '/dist',
    filename: 'bundle.js',
  },

  resolve: {
    modulesDirectories: ['node_modules', './src'],  // import时到哪些地方去寻找模块
    extensions: ['', '.js', '.jsx'],  // require的时候可以直接使用require('file')，不用require('file.js')
    alias: {
      antdcss: 'antd/dist/antd.min.css',  // import时的别名
    },
  },

  module: {
    loaders: [  // 定义各种loader
      {
        test: /\.jsx?$/,
        loaders: ['react-hot', 'babel-loader?' + JSON.stringify(babelLoaderConfig)],  // react-hot-loader可以不用刷新页面, 如果用普通的dev-server的话会自动刷新页面
        exclude: /node_modules/,
      }, {
        test: /\.css$/,
        loader: 'style!css',
      }, {
        test: /\.less$/,
        loader: 'style!css!less',  // 用!去链式调用loader
      }, {
        test: /\.(png|jpg|svg)$/,
        loader: 'url?limit=25000',  // 图片小于一定值的话转成base64
      },
    ],
  },

  plugins: [
    new webpack.BannerPlugin('This file is created by jxy'),   // 生成文件时加上注释
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development'),
      __DEV__: JSON.stringify(JSON.parse(process.env.NODE_ENV === 'production' ? 'false' : 'true')),  // magic globals, 用于打印一些调试的日志, webpack -p时会删除
    }),
  ],
};
<commit_msg>bugfix<commit_after>const webpack = require('webpack');

// 将babel-loader的配置独立出来, 因为webpack的限制: http://stackoverflow.com/questions/33117136/how-to-add-a-query-to-a-webpack-loader-with-multiple-loaders
const babelLoaderConfig = {
  presets: ['latest', 'stage-0', 'react'],  // 开启ES6、部分ES7、react特性, preset相当于预置的插件集合
  plugins: [['import', {libraryName: 'antd', style: true}]],  // antd模块化加载, https://github.com/ant-design/babel-plugin-import
  cacheDirectory: true,
};

module.exports = {
  devtool: 'eval-source-map',

  entry: [
    'webpack-dev-server/client?http://0.0.0.0:8080', // WebpackDevServer host and port
    'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
    'babel-polyfill',  // 可以使用完整的ES6特性, 大概增加100KB
    './src/index.js',  // 编译的入口
  ],

  output: {  // 输出的目录和文件名
    path: __dirname + '/dist',
    filename: 'bundle.js',
  },

  resolve: {
    modulesDirectories: ['node_modules', './src'],  // import时到哪些地方去寻找模块
    extensions: ['', '.js', '.jsx'],  // require的时候可以直接使用require('file')，不用require('file.js')
    alias: {
      antdcss: 'antd/dist/antd.min.css',  // import时的别名
    },
  },

  module: {
    loaders: [  // 定义各种loader
      {
        test: /\.jsx?$/,
        loaders: ['react-hot', 'babel-loader?' + JSON.stringify(babelLoaderConfig)],  // react-hot-loader可以不用刷新页面, 如果用普通的dev-server的话会自动刷新页面
        exclude: /node_modules/,
      }, {
        test: /\.css$/,
        loader: 'style!css',
      }, {
        test: /\.less$/,
        loader: 'style!css!less?{"sourceMap":true}',  // 用!去链式调用loader
      }, {
        test: /\.(png|jpg|svg)$/,
        loader: 'url?limit=25000',  // 图片小于一定值的话转成base64
      },
    ],
  },

  plugins: [
    new webpack.BannerPlugin('This file is created by jxy'),   // 生成文件时加上注释
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development'),
      __DEV__: JSON.stringify(JSON.parse(process.env.NODE_ENV === 'production' ? 'false' : 'true')),  // magic globals, 用于打印一些调试的日志, webpack -p时会删除
    }),
  ],
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-2016 Memba Sarl. All rights reserved.
 * Sources at https://github.com/Memba
 */

/* jshint node: true */

'use strict';

/**
 * For an introduction to WebPack
 * @see https://github.com/petehunt/webpack-howto
 * @see http://slidedeck.io/unindented/webpack-presentation
 * @see http://christianalfoni.github.io/javascript/2014/12/13/did-you-know-webpack-and-react-is-awesome.html
 */

var path = require('path');
var util = require('util');

var webpack = require('webpack');
var config = require('./webapp/config');

/**
 * definePlugin defines a global variable which is only available when running webpack
 * We use it to merge app.config.jsx with the proper
 * @type {webpack.DefinePlugin}
 * @see http://webpack.github.io/docs/list-of-plugins.html#defineplugin
 * @see https://github.com/petehunt/webpack-howto#6-feature-flags
 */
var pkg = require('./package.json');
var environment = config.environment || 'development';
var definePlugin = new webpack.DefinePlugin({
    __NODE_ENV__: JSON.stringify(environment),
    __VERSION__: JSON.stringify(pkg.version)
});
console.log('webpack environment is ' + environment);
console.log('webpack public path is ' + config.get('uris:webpack:root'));
console.log('building version ' + pkg.version);

/**
 * commonsChunkPlugin builds a common denominator of the designated chunks
 */
var commonsChunkPlugin =
    new webpack.optimize.CommonsChunkPlugin({ name: 'common', filename: 'common.bundle.js', chunks: ['error', 'home', 'post', 'page', 'search'] });

/**
 * Add banner at the top of every bundle/chunk
 */
var bannerPlugin =
    new webpack.BannerPlugin({ banner: pkg.copyright + ' - Version ' + pkg.version + ' dated ' + new Date().toLocaleDateString(), raw: true, entryOnly: true });

/**
 * SourceMapDevToolPlugin builds source maps
 * For debugging in WebStorm see https://github.com/webpack/webpack/issues/238
 *
 * var sourceMapDevToolPlugin = new webpack.SourceMapDevToolPlugin(
 *     '[file].map', null,
 *     "[absolute-resource-path]", "[absolute-resource-path]"
 * );
 *
 * We are not using the source map plugin since webpack -d on the command line
 * produces sourcemaps in our development environment and we do not want sourcemaps in production.
 */

/**
 * Webpack configuration
 * @see https://github.com/webpack/docs/wiki/configuration
 */
module.exports = {
    // All paths below are relative to the context
    context: path.join(__dirname, '/'),
    devtool: 'source-map',
    entry: {
        // We need init especially because of FOUJI
        init:   './js/app.init.js',
        // One entry per view
        error:  './js/app.error.js',
        home:   './js/app.home.js',
        page:   './js/app.page.js',
        post:   './js/app.post.js',
        search: './js/app.search.js'
    },
    externals: { // CDN modules
        jquery: 'jQuery'
    },
    output: {
        // Unfortunately it is not possible to specialize output directories
        // See https://github.com/webpack/webpack/issues/882
        path: path.join(__dirname, '/webapp/public/build'),
        publicPath: config.get('uris:webpack:root'),
        filename: '[name].bundle.js?v=' + pkg.version,
        chunkFilename: '[name].chunk.js?v=' + pkg.version
    },
    resolve: {
        modules: [
            path.resolve('.'),
            path.resolve('./js/vendor/kendo'), // required since Kendo UI 2016.1.112
            'node_modules'
        ]
    },
    module: {
        rules: [
            {
                // Do not put a $ at the end of the test regex
                test: /\.jsx/, // see ./web_modules/jsx-loader
                use: [
                    { loader: './web_modules/jsx-loader', options: { config: 'webapp/config' } }
                ]
            },
            {
                test: /\.json$/,
                use: [
                    { loader: 'json-loader' }
                ]
            },
            {
                test: /app\.theme\.[a-z0-9]+\.less$/,
                use: [
                    // { loader: 'bundle-loader', options: { name: '[name]' } },
                    { loader: 'bundle-loader?name=[name]' },
                    // { loader: "style-loader", options: { useable: true } },
                    { loader: "style-loader/useable" },
                    { loader: 'css-loader', options: { importLoaders: 2 } },
                    { loader: 'postcss-loader' },
                    // See https://github.com/jlchereau/Kidoju-Webapp/issues/197
                    // { loader: 'less-loader', options: { compress: true, relativeUrls: true, strictMath: true } }
                    { loader: 'less-loader' }
                ]
            },
            {
                test: /\.less$/,
                exclude: /app\.theme\.[a-z0-9]+\.less$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader', options: { importLoaders: 1 } },
                    { loader: 'postcss-loader' },
                    // See https://github.com/jlchereau/Kidoju-Webapp/issues/197
                    // { loader: 'less-loader', options: { compress: true, relativeUrls: true, strictMath: true } }
                    { loader: 'less-loader' }
                ]
            },
            {
                test: /\.css$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader', options: { importLoaders: 1 } },
                    { loader: 'postcss-loader' }
                ]
            },
            {
                test: /\.(gif|png|jpe?g)$/,
                use: [
                    // { loader: 'url-loader', options: { limit: 8192 } }
                    { loader: 'url-loader?limit=8192' }
                ]
            },
            {
                test: /\.woff(2)?/,
                use: [
                    // { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } }
                    { loader: 'url-loader?limit=10000&mimetype=application/font-woff' }
                ]
            },
            {
                test: /\.(ttf|eot|svg)/,
                use: [
                    { loader: 'file-loader' }
                ]
            }
        ]
    },
    plugins: [
        definePlugin,
        commonsChunkPlugin
        // bannerPlugin breaks uglifyJS
    ]
};
<commit_msg>Fixed jshint and jscs errors<commit_after>/**
 * Copyright (c) 2013-2016 Memba Sarl. All rights reserved.
 * Sources at https://github.com/Memba
 */

/* jshint node: true */

'use strict';

/**
 * For an introduction to WebPack
 * @see https://github.com/petehunt/webpack-howto
 * @see http://slidedeck.io/unindented/webpack-presentation
 * @see http://christianalfoni.github.io/javascript/2014/12/13/did-you-know-webpack-and-react-is-awesome.html
 */

var path = require('path');
var util = require('util');

var webpack = require('webpack');
var config = require('./webapp/config');

/**
 * definePlugin defines a global variable which is only available when running webpack
 * We use it to merge app.config.jsx with the proper
 * @type {webpack.DefinePlugin}
 * @see http://webpack.github.io/docs/list-of-plugins.html#defineplugin
 * @see https://github.com/petehunt/webpack-howto#6-feature-flags
 */
var pkg = require('./package.json');
var environment = config.environment || 'development';
var definePlugin = new webpack.DefinePlugin({
    __NODE_ENV__: JSON.stringify(environment),
    __VERSION__: JSON.stringify(pkg.version)
});
console.log('webpack environment is ' + environment);
console.log('webpack public path is ' + config.get('uris:webpack:root'));
console.log('building version ' + pkg.version);

/**
 * commonsChunkPlugin builds a common denominator of the designated chunks
 */
var commonsChunkPlugin =
    new webpack.optimize.CommonsChunkPlugin({ name: 'common', filename: 'common.bundle.js', chunks: ['error', 'home', 'post', 'page', 'search'] });

/**
 * Add banner at the top of every bundle/chunk
 */
var bannerPlugin =
    new webpack.BannerPlugin({ banner: pkg.copyright + ' - Version ' + pkg.version + ' dated ' + new Date().toLocaleDateString(), raw: true, entryOnly: true });

/**
 * SourceMapDevToolPlugin builds source maps
 * For debugging in WebStorm see https://github.com/webpack/webpack/issues/238
 *
 * var sourceMapDevToolPlugin = new webpack.SourceMapDevToolPlugin(
 *     '[file].map', null,
 *     "[absolute-resource-path]", "[absolute-resource-path]"
 * );
 *
 * We are not using the source map plugin since webpack -d on the command line
 * produces sourcemaps in our development environment and we do not want sourcemaps in production.
 */

/**
 * Webpack configuration
 * @see https://github.com/webpack/docs/wiki/configuration
 */
module.exports = {
    // All paths below are relative to the context
    context: path.join(__dirname, '/'),
    devtool: 'source-map',
    entry: {
        // We need init especially because of FOUJI
        init:   './js/app.init.js',
        // One entry per view
        error:  './js/app.error.js',
        home:   './js/app.home.js',
        page:   './js/app.page.js',
        post:   './js/app.post.js',
        search: './js/app.search.js'
    },
    externals: { // CDN modules
        jquery: 'jQuery'
    },
    output: {
        // Unfortunately it is not possible to specialize output directories
        // See https://github.com/webpack/webpack/issues/882
        path: path.join(__dirname, '/webapp/public/build'),
        publicPath: config.get('uris:webpack:root'),
        filename: '[name].bundle.js?v=' + pkg.version,
        chunkFilename: '[name].chunk.js?v=' + pkg.version
    },
    resolve: {
        modules: [
            path.resolve('.'),
            path.resolve('./js/vendor/kendo'), // required since Kendo UI 2016.1.112
            'node_modules'
        ]
    },
    module: {
        rules: [
            {
                // Do not put a $ at the end of the test regex
                test: /\.jsx/, // see ./web_modules/jsx-loader
                use: [
                    { loader: './web_modules/jsx-loader', options: { config: 'webapp/config' } }
                ]
            },
            {
                test: /\.json$/,
                use: [
                    { loader: 'json-loader' }
                ]
            },
            {
                test: /app\.theme\.[a-z0-9]+\.less$/,
                use: [
                    // { loader: 'bundle-loader', options: { name: '[name]' } },
                    { loader: 'bundle-loader?name=[name]' },
                    // { loader: "style-loader", options: { useable: true } },
                    { loader: 'style-loader/useable' },
                    { loader: 'css-loader', options: { importLoaders: 2 } },
                    { loader: 'postcss-loader' },
                    // See https://github.com/jlchereau/Kidoju-Webapp/issues/197
                    // { loader: 'less-loader', options: { compress: true, relativeUrls: true, strictMath: true } }
                    { loader: 'less-loader' }
                ]
            },
            {
                test: /\.less$/,
                exclude: /app\.theme\.[a-z0-9]+\.less$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader', options: { importLoaders: 1 } },
                    { loader: 'postcss-loader' },
                    // See https://github.com/jlchereau/Kidoju-Webapp/issues/197
                    // { loader: 'less-loader', options: { compress: true, relativeUrls: true, strictMath: true } }
                    { loader: 'less-loader' }
                ]
            },
            {
                test: /\.css$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader', options: { importLoaders: 1 } },
                    { loader: 'postcss-loader' }
                ]
            },
            {
                test: /\.(gif|png|jpe?g)$/,
                use: [
                    // { loader: 'url-loader', options: { limit: 8192 } }
                    { loader: 'url-loader?limit=8192' }
                ]
            },
            {
                test: /\.woff(2)?/,
                use: [
                    // { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } }
                    { loader: 'url-loader?limit=10000&mimetype=application/font-woff' }
                ]
            },
            {
                test: /\.(ttf|eot|svg)/,
                use: [
                    { loader: 'file-loader' }
                ]
            }
        ]
    },
    plugins: [
        definePlugin,
        commonsChunkPlugin
        // bannerPlugin breaks uglifyJS
    ]
};
<|endoftext|>


<commit_before>var webpack = require('webpack');
var _ = require('underscore');

module.exports = {
  debug: true,
  context: __dirname,
  // the arrays are a weird workaround the "a dependency to an entry point is not allowed" error
  // https://github.com/webpack/webpack/issues/300#issuecomment-45313650
  entry: {
    app: ['./app/app'],
    'app-complete': './app/app_main_complete.entry',
    test: './test/run_mocha_browser'
  },
  output: {
    path: __dirname + "/build/web",
    filename: "lead-[name].js"
  },
  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.js', '.web.coffee', '.coffee', '.cjsx'],
    alias: {
      // bacon.model references 'baconjs' in commonjs and 'bacon' in amd
      'bacon': 'baconjs',
      'coffee-script': __dirname + '/lib/coffee-script',
    }
  },
  module: {
    loaders: [
      {test: /\.coffee$/, loader: "coffee-loader"},
      {test: /\.cjsx$/, loader: 'coffee-loader!' + __dirname + '/lib/coffee-react-transform-loader.coffee'},
      {test: /\.jsx?$/, exclude: /(node_modules|lib)/, loader: 'babel-loader?optional=runtime&optional=reactCompat'},

      // shims
      {test: /baconjs/, loader: 'imports?jQuery=jquery'},
      {test: /coffee-script.js$/, loader: 'exports?exports.CoffeeScript'},
      { test: /font-awesome\/fonts\/.+\.(ttf|woff|eot|svg)$/, loader: "file-loader?name=fonts/[name]-[hash].[ext]" },
    ],
    // TODO coffeescript has a weird require browser
    noParse: /coffee-script.js$/
  },
  plugins: [
    // only include the moment english language
    new webpack.ContextReplacementPlugin(/moment[\\\/]lang$/, /^\.\/(en)$/),

    // no "." and no subdirectories in ./app context. this excludes .entry.coffee files, and files that don't match extensions
    new webpack.ContextReplacementPlugin(/\/app$/, false, /^\.\/[^.]*$/),
    new webpack.NormalModuleReplacementPlugin(/^\.\/lib\/colorbrewer$/, '../lib/colorbrewer')
  ],
  integrate: function (directory) {
    var result = _.clone(module.exports);
    result.resolve.root = [__dirname + '/node_modules', directory + '/node_modules'];
    result.resolve.alias['lead.js'] = __dirname + '/app';
    result.resolveLoader = {root: result.resolve.root};
    return result;
  }
}
<commit_msg>fix webpack config<commit_after>var webpack = require('webpack');
var _ = require('underscore');

module.exports = {
  debug: true,
  context: __dirname,
  // the arrays are a weird workaround the "a dependency to an entry point is not allowed" error
  // https://github.com/webpack/webpack/issues/300#issuecomment-45313650
  entry: {
    app: ['./app/app'],
    'app-complete': './app/app_main_complete.entry',
    test: './test/run_mocha_browser'
  },
  output: {
    path: __dirname + "/build/web",
    filename: "lead-[name].js"
  },
  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.js', '.web.coffee', '.coffee', '.cjsx'],
    alias: {
      // bacon.model references 'baconjs' in commonjs and 'bacon' in amd
      'bacon': 'baconjs',
      'coffee-script': __dirname + '/lib/coffee-script',
    }
  },
  module: {
    loaders: [
      {test: /\.coffee$/, loader: "coffee-loader"},
      {test: /\.cjsx$/, loader: 'coffee-loader!' + __dirname + '/lib/coffee-react-transform-loader.coffee'},
      {test: /\.jsx?$/, exclude: /(node_modules|lib)/, loader: 'babel', query: {optional: ['runtime', 'reactCompat']}},

      // shims
      {test: /baconjs/, loader: 'imports?jQuery=jquery'},
      {test: /coffee-script.js$/, loader: 'exports?exports.CoffeeScript'},
      { test: /font-awesome\/fonts\/.+\.(ttf|woff|eot|svg)$/, loader: "file-loader?name=fonts/[name]-[hash].[ext]" }
    ],
    // TODO coffeescript has a weird require browser
    noParse: /coffee-script.js$/
  },
  plugins: [
    // only include the moment english language
    new webpack.ContextReplacementPlugin(/moment[\\\/]lang$/, /^\.\/(en)$/),

    // no "." and no subdirectories in ./app context. this excludes .entry.coffee files, and files that don't match extensions
    new webpack.ContextReplacementPlugin(/\/app$/, false, /^\.\/[^.]*$/),
    new webpack.NormalModuleReplacementPlugin(/^\.\/lib\/colorbrewer$/, '../lib/colorbrewer')
  ],
  integrate: function (directory) {
    var result = _.clone(module.exports);
    result.resolve.root = [__dirname + '/node_modules', directory + '/node_modules'];
    result.resolve.alias['lead.js'] = __dirname + '/app';
    result.resolveLoader = {root: result.resolve.root};
    return result;
  }
}
<|endoftext|>


<commit_before>const path = require('path');
const fs = require('fs');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './client/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: './client/index.js',
  output: {
    path: path.resolve('dist'),
    filename: 'index_bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.svg$/,
        loader: 'svg-url-loader'
      },
      {
        test: /\.s?css$/,
        loader: [
          'style-loader?sourceMap',
          'css-loader',
          'sass-loader?sourceMap'
        ]
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        loader: 'file-loader?name=public/fonts/[name].[ext]'
      }
    ]
  },
  plugins: [HtmlWebpackPluginConfig]
}
<commit_msg>Updated webpack.config for gh-ages<commit_after>const path = require('path');
const fs = require('fs');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './client/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: './client/index.js',
  output: {
    path: path.resolve('./'),
    filename: 'index_bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.svg$/,
        loader: 'svg-url-loader'
      },
      {
        test: /\.s?css$/,
        loader: [
          'style-loader?sourceMap',
          'css-loader',
          'sass-loader?sourceMap'
        ]
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        loader: 'file-loader?name=public/fonts/[name].[ext]'
      }
    ]
  },
  plugins: [HtmlWebpackPluginConfig]
}
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const proxy = require('./server/webpack-dev-proxy');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const SplitByPathPlugin = require('webpack-split-by-path');

const loaders = require('./webpack/loaders');

const basePlugins = [
  new webpack.DefinePlugin({
    __DEV__: process.env.NODE_ENV !== 'production',
    __PRODUCTION__: process.env.NODE_ENV === 'production',
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
  }),
  new SplitByPathPlugin([
    { name: 'vendor', path: [__dirname + '/node_modules/'] },
  ]),
  new HtmlWebpackPlugin({
    template: './src/index.html',
    inject: 'body',
    minify: false,
  }),
  new webpack.NoErrorsPlugin(),
];

const devPlugins = [
  new StyleLintPlugin({
    configFile: './.stylelintrc',
    files: 'src/**/*.css',
    failOnError: false,
  }),
];

const prodPlugins = [
  new webpack.optimize.OccurenceOrderPlugin(),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin({
    mangle: true,
    compress: {
      warnings: false,
    },
  }),
];

const plugins = basePlugins
  .concat(process.env.NODE_ENV === 'production' ? prodPlugins : [])
  .concat(process.env.NODE_ENV === 'development' ? devPlugins : []);

const postcssBasePlugins = [
  require('postcss-import')({
    addDependencyTo: webpack,
  }),
  require('postcss-cssnext')({
    browsers: ['ie >= 8', 'last 2 versions'],
  }),
];
const postcssDevPlugins = [];
const postcssProdPlugins = [
  require('cssnano')({
    safe: true,
    sourcemap: true,
    autoprefixer: false,
  }),
];

const postcssPlugins = postcssBasePlugins
  .concat(process.env.NODE_ENV === 'production' ? postcssProdPlugins : [])
  .concat(process.env.NODE_ENV === 'development' ? postcssDevPlugins : []);

module.exports = {
  entry: {
    app: './src/index.ts',
  },

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[hash].js',
    publicPath: '/',
    sourceMapFilename: '[name].[hash].js.map',
    chunkFilename: '[id].chunk.js',
  },

  devtool: process.env.NODE_ENV === 'production' ?
    'source-map' :
    'inline-source-map',

  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.ts', '.js'],
    alias: {
      'p5sound': 'p5/lib/addons/p5.sound.js',
    },
  },

  plugins: plugins,

  devServer: {
    historyApiFallback: { index: '/' },
    proxy: Object.assign({}, proxy(), { '*': 'http://localhost:3000' }),
  },

  module: {
    preLoaders: [
      loaders.tslint,
    ],
    loaders: [
      {
        test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/font-woff',
      }, {
        test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/font-woff',
      }, {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/octet-stream',
      }, {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file',
      }, {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=image/svg+xml',
      },
      loaders.ts,
      loaders.html,
      loaders.css,
      loaders.svg,
      // loaders.eot,
      // loaders.woff,
      // loaders.woff2,
      // loaders.ttf,
    ],
    noParse: [ /zone\.js\/dist\/.+/, /angular2\/bundles\/.+/ ],
  },

  postcss: function postcssInit() {
    return postcssPlugins;
  },
};
<commit_msg>Fix relative paths<commit_after>'use strict';

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const proxy = require('./server/webpack-dev-proxy');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const SplitByPathPlugin = require('webpack-split-by-path');

const loaders = require('./webpack/loaders');

const basePlugins = [
  new webpack.DefinePlugin({
    __DEV__: process.env.NODE_ENV !== 'production',
    __PRODUCTION__: process.env.NODE_ENV === 'production',
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
  }),
  new SplitByPathPlugin([
    { name: 'vendor', path: [__dirname + '/node_modules/'] },
  ]),
  new HtmlWebpackPlugin({
    template: './src/index.html',
    inject: 'body',
    minify: false,
  }),
  new webpack.NoErrorsPlugin(),
];

const devPlugins = [
  new StyleLintPlugin({
    configFile: './.stylelintrc',
    files: 'src/**/*.css',
    failOnError: false,
  }),
];

const prodPlugins = [
  new webpack.optimize.OccurenceOrderPlugin(),
  new webpack.optimize.DedupePlugin(),
  new webpack.optimize.UglifyJsPlugin({
    mangle: true,
    compress: {
      warnings: false,
    },
  }),
];

const plugins = basePlugins
  .concat(process.env.NODE_ENV === 'production' ? prodPlugins : [])
  .concat(process.env.NODE_ENV === 'development' ? devPlugins : []);

const postcssBasePlugins = [
  require('postcss-import')({
    addDependencyTo: webpack,
  }),
  require('postcss-cssnext')({
    browsers: ['ie >= 8', 'last 2 versions'],
  }),
];
const postcssDevPlugins = [];
const postcssProdPlugins = [
  require('cssnano')({
    safe: true,
    sourcemap: true,
    autoprefixer: false,
  }),
];

const postcssPlugins = postcssBasePlugins
  .concat(process.env.NODE_ENV === 'production' ? postcssProdPlugins : [])
  .concat(process.env.NODE_ENV === 'development' ? postcssDevPlugins : []);

module.exports = {
  entry: {
    app: './src/index.ts',
  },

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[hash].js',
    publicPath: '',
    sourceMapFilename: '[name].[hash].js.map',
    chunkFilename: '[id].chunk.js',
  },

  devtool: process.env.NODE_ENV === 'production' ?
    'source-map' :
    'inline-source-map',

  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.ts', '.js'],
    alias: {
      'p5sound': 'p5/lib/addons/p5.sound.js',
    },
  },

  plugins: plugins,

  devServer: {
    historyApiFallback: { index: '/' },
    proxy: Object.assign({}, proxy(), { '*': 'http://localhost:3000' }),
  },

  module: {
    preLoaders: [
      loaders.tslint,
    ],
    loaders: [
      {
        test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/font-woff',
      }, {
        test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/font-woff',
      }, {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=application/octet-stream',
      }, {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file',
      }, {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url?limit=10000&mimetype=image/svg+xml',
      },
      loaders.ts,
      loaders.html,
      loaders.css,
      loaders.svg,
      // loaders.eot,
      // loaders.woff,
      // loaders.woff2,
      // loaders.ttf,
    ],
    noParse: [ /zone\.js\/dist\/.+/, /angular2\/bundles\/.+/ ],
  },

  postcss: function postcssInit() {
    return postcssPlugins;
  },
};
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: {
    app: './resource/js/app.js',
    crowi: './resource/js/crowi.js',
    presentation: './resource/js/crowi-presentation.js',
    form: './resource/js/crowi-form.js',
    admin: './resource/js/crowi-admin.js',
  },
  output: {
    path: path.join(__dirname + "/public/js"),
    filename: "[name].js"
  },
  resolve: {
    modulesDirectories: [
      './node_modules', './resource/thirdparty-js',
    ],
  },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
  plugins: [
    //new webpack.ProvidePlugin({
    //  jQuery: "jquery",
    //  $: "jquery",
    //  jqeury: "jquery",
    //}),
    //new webpack.optimize.DedupePlugin(),
  ]
};
<commit_msg>Should be separate file on dev/prod webpack config for real<commit_after>var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: {
    app: './resource/js/app.js',
    crowi: './resource/js/crowi.js',
    presentation: './resource/js/crowi-presentation.js',
    form: './resource/js/crowi-form.js',
    admin: './resource/js/crowi-admin.js',
  },
  output: {
    path: path.join(__dirname + "/public/js"),
    filename: "[name].js"
  },
  resolve: {
    modulesDirectories: [
      './node_modules', './resource/thirdparty-js',
    ],
  },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env": {
        NODE_ENV: JSON.stringify("production")
      }
    })
    //new webpack.ProvidePlugin({
    //  jQuery: "jquery",
    //  $: "jquery",
    //  jqeury: "jquery",
    //}),
    //new webpack.optimize.DedupePlugin(),
  ]
};
<|endoftext|>


<commit_before>module.exports = {
  entry: {
    'build/inject': './src/inject/index',
  },
  output: {
    path: './',
    filename: '[name].js'
  },
  watch: true,
  cache: true,
  node: {
    fs: 'empty'
  }
}
<commit_msg>Delete webpack.config.js<commit_after><|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import {withRouter} from 'react-router'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'

import {MEMBER_ROLE, VIEWER_ROLE} from 'src/auth/Authorized'

import {getSources} from 'shared/apis'
import {showDatabases} from 'shared/apis/metaQuery'

import {loadSources as loadSourcesAction} from 'shared/actions/sources'
import {errorThrown as errorThrownAction} from 'shared/actions/errors'

import {DEFAULT_HOME_PAGE} from 'shared/constants'

// Acts as a 'router middleware'. The main `App` component is responsible for
// getting the list of data nodes, but not every page requires them to function.
// Routes that do require data nodes can be nested under this component.
const {arrayOf, bool, func, node, shape, string} = PropTypes
const CheckSources = React.createClass({
  propTypes: {
    sources: arrayOf(
      shape({
        links: shape({
          proxy: string.isRequired,
          self: string.isRequired,
          kapacitors: string.isRequired,
          queries: string.isRequired,
          permissions: string.isRequired,
          users: string.isRequired,
          databases: string.isRequired,
        }).isRequired,
      })
    ),
    children: node,
    params: shape({
      sourceID: string,
    }).isRequired,
    router: shape({
      push: func.isRequired,
    }).isRequired,
    location: shape({
      pathname: string.isRequired,
    }).isRequired,
    loadSources: func.isRequired,
    errorThrown: func.isRequired,
    auth: shape({
      isUsingAuth: bool,
      me: shape(),
    }),
  },

  childContextTypes: {
    source: shape({
      links: shape({
        proxy: string.isRequired,
        self: string.isRequired,
        kapacitors: string.isRequired,
        queries: string.isRequired,
        permissions: string.isRequired,
        users: string.isRequired,
        databases: string.isRequired,
      }).isRequired,
    }),
  },

  getChildContext() {
    const {sources, params: {sourceID}} = this.props
    return {source: sources.find(s => s.id === sourceID)}
  },

  getInitialState() {
    return {
      isFetching: true,
    }
  },

  async componentWillMount() {
    const {loadSources, errorThrown} = this.props

    try {
      const {data: {sources}} = await getSources()
      loadSources(sources)
      this.setState({isFetching: false})
    } catch (error) {
      errorThrown(error, 'Unable to connect to Chronograf server')
      this.setState({isFetching: false})
    }
  },

  async componentWillUpdate(nextProps, nextState) {
    const {
      router,
      location,
      params,
      errorThrown,
      sources,
      auth: {isUsingAuth, me},
    } = nextProps
    const {isFetching} = nextState
    const source = sources.find(s => s.id === params.sourceID)
    const defaultSource = sources.find(s => s.default === true)

    if (!isFetching && !source) {
      const rest = location.pathname.match(/\/sources\/\d+?\/(.+)/)
      const restString = rest === null ? DEFAULT_HOME_PAGE : rest[1]

      if (isUsingAuth && me.role === MEMBER_ROLE) {
        // if you're a member, go to limbo.
        return router.push('/limbo')
      }

      if (isUsingAuth && me.role === VIEWER_ROLE) {
        if (defaultSource) {
          return router.push(`/sources/${defaultSource.id}/${restString}`)
        } else if (sources[0]) {
          return router.push(`/sources/${sources[0].id}/${restString}`)
        }
        // if you're a viewer and there are no sources, go to limbo.
        return router.push('/limbo')
      }

      // if you're an editor or not using auth, try for sources or otherwise
      // create one
      if (defaultSource) {
        return router.push(`/sources/${defaultSource.id}/${restString}`)
      } else if (sources[0]) {
        return router.push(`/sources/${sources[0].id}/${restString}`)
      }

      return router.push(`/sources/new?redirectPath=${location.pathname}`)
    }

    if (!isFetching && !location.pathname.includes('/manage-sources')) {
      // Do simple query to proxy to see if the source is up.
      try {
        await showDatabases(source.links.proxy)
      } catch (error) {
        errorThrown(error, 'Unable to connect to source')
      }
    }
  },

  render() {
    const {params, sources, auth: {isUsingAuth, me}} = this.props
    const {isFetching} = this.state
    const source = sources.find(s => s.id === params.sourceID)

    if (
      isFetching ||
      !source ||
      typeof isUsingAuth !== 'boolean' ||
      (me && me.role === undefined) // TODO: not sure this happens
    ) {
      return

    }

    return (
      this.props.children &&
      React.cloneElement(
        this.props.children,
        Object.assign({}, this.props, {
          source,
        })
      )
    )
  },
})

const mapStateToProps = ({sources, auth, me}) => ({
  sources,
  auth,
  me,
})

const mapDispatchToProps = dispatch => ({
  loadSources: bindActionCreators(loadSourcesAction, dispatch),
  errorThrown: bindActionCreators(errorThrownAction, dispatch),
})

export default connect(mapStateToProps, mapDispatchToProps)(
  withRouter(CheckSources)
)
<commit_msg>Redirect lost souls to purgatory not limbo<commit_after>import React, {PropTypes} from 'react'
import {withRouter} from 'react-router'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'

import {MEMBER_ROLE, VIEWER_ROLE} from 'src/auth/Authorized'

import {getSources} from 'shared/apis'
import {showDatabases} from 'shared/apis/metaQuery'

import {loadSources as loadSourcesAction} from 'shared/actions/sources'
import {errorThrown as errorThrownAction} from 'shared/actions/errors'

import {DEFAULT_HOME_PAGE} from 'shared/constants'

// Acts as a 'router middleware'. The main `App` component is responsible for
// getting the list of data nodes, but not every page requires them to function.
// Routes that do require data nodes can be nested under this component.
const {arrayOf, bool, func, node, shape, string} = PropTypes
const CheckSources = React.createClass({
  propTypes: {
    sources: arrayOf(
      shape({
        links: shape({
          proxy: string.isRequired,
          self: string.isRequired,
          kapacitors: string.isRequired,
          queries: string.isRequired,
          permissions: string.isRequired,
          users: string.isRequired,
          databases: string.isRequired,
        }).isRequired,
      })
    ),
    children: node,
    params: shape({
      sourceID: string,
    }).isRequired,
    router: shape({
      push: func.isRequired,
    }).isRequired,
    location: shape({
      pathname: string.isRequired,
    }).isRequired,
    loadSources: func.isRequired,
    errorThrown: func.isRequired,
    auth: shape({
      isUsingAuth: bool,
      me: shape(),
    }),
  },

  childContextTypes: {
    source: shape({
      links: shape({
        proxy: string.isRequired,
        self: string.isRequired,
        kapacitors: string.isRequired,
        queries: string.isRequired,
        permissions: string.isRequired,
        users: string.isRequired,
        databases: string.isRequired,
      }).isRequired,
    }),
  },

  getChildContext() {
    const {sources, params: {sourceID}} = this.props
    return {source: sources.find(s => s.id === sourceID)}
  },

  getInitialState() {
    return {
      isFetching: true,
    }
  },

  async componentWillMount() {
    const {loadSources, errorThrown} = this.props

    try {
      const {data: {sources}} = await getSources()
      loadSources(sources)
      this.setState({isFetching: false})
    } catch (error) {
      errorThrown(error, 'Unable to connect to Chronograf server')
      this.setState({isFetching: false})
    }
  },

  async componentWillUpdate(nextProps, nextState) {
    const {
      router,
      location,
      params,
      errorThrown,
      sources,
      auth: {isUsingAuth, me},
    } = nextProps
    const {isFetching} = nextState
    const source = sources.find(s => s.id === params.sourceID)
    const defaultSource = sources.find(s => s.default === true)

    if (!isFetching && !source) {
      const rest = location.pathname.match(/\/sources\/\d+?\/(.+)/)
      const restString = rest === null ? DEFAULT_HOME_PAGE : rest[1]

      if (isUsingAuth && me.role === MEMBER_ROLE) {
        // if you're a member, go to purgatory.
        return router.push('/purgatory')
      }

      if (isUsingAuth && me.role === VIEWER_ROLE) {
        if (defaultSource) {
          return router.push(`/sources/${defaultSource.id}/${restString}`)
        } else if (sources[0]) {
          return router.push(`/sources/${sources[0].id}/${restString}`)
        }
        // if you're a viewer and there are no sources, go to purgatory.
        return router.push('/purgatory')
      }

      // if you're an editor or not using auth, try for sources or otherwise
      // create one
      if (defaultSource) {
        return router.push(`/sources/${defaultSource.id}/${restString}`)
      } else if (sources[0]) {
        return router.push(`/sources/${sources[0].id}/${restString}`)
      }

      return router.push(`/sources/new?redirectPath=${location.pathname}`)
    }

    if (!isFetching && !location.pathname.includes('/manage-sources')) {
      // Do simple query to proxy to see if the source is up.
      try {
        await showDatabases(source.links.proxy)
      } catch (error) {
        errorThrown(error, 'Unable to connect to source')
      }
    }
  },

  render() {
    const {params, sources, auth: {isUsingAuth, me}} = this.props
    const {isFetching} = this.state
    const source = sources.find(s => s.id === params.sourceID)

    if (
      isFetching ||
      !source ||
      typeof isUsingAuth !== 'boolean' ||
      (me && me.role === undefined) // TODO: not sure this happens
    ) {
      return

    }

    return (
      this.props.children &&
      React.cloneElement(
        this.props.children,
        Object.assign({}, this.props, {
          source,
        })
      )
    )
  },
})

const mapStateToProps = ({sources, auth, me}) => ({
  sources,
  auth,
  me,
})

const mapDispatchToProps = dispatch => ({
  loadSources: bindActionCreators(loadSourcesAction, dispatch),
  errorThrown: bindActionCreators(errorThrownAction, dispatch),
})

export default connect(mapStateToProps, mapDispatchToProps)(
  withRouter(CheckSources)
)
<|endoftext|>


<commit_before>'use strict';

const init = require('../base/init');
const error = require('../base/error');
const config = require('../base/config');
const date2 = require('../base/date2');
const url2 = require('../base/url2');
const mysql2 = require('../mysql/mysql2');
const expb = require('../express/express-base');
const userb = require('../user/user-base');
const postb = require('./post-base');
const postsr = exports;

postsr.updateThread = function (tid, done) {
  mysql2.queryOne('select * from thread where id = ?', tid, (err, thread) => {
    if (err) return done(err);
    thread.merged = thread.writer + ' ' + thread.title + ' ';
    mysql2.query('select * from post where tid = ?', tid, (err, r) => {
      if (err) return done(err);
        r.forEach((post) => {
        thread.merged += post.text + " " + post.writer + " ";
        if (!thread.text) {
          thread.text = post.text.slice(0, 255);
        }
      });
      mysql2.query(
        'delete from threadmerged where id = ?;' +
        'insert into threadmerged set ?',
        [tid, thread],
        done);
    });
  });
};

var updateThread = postsr.updateThread;

postsr.updateAll = function (done) {
  let offset = 0;
  let ps = 100;
  (function loop1() {
    mysql2.query('select id from thread order by id limit ?, ?', [offset, ps], (err, threads) => {
      if (err) return done(err);
      if (!threads.length) return done();
      if (postsr.updateAll.showProgress) {
        process.stdout.write(offset + ' ');
      }
      offset += ps;
      let i = 0;
      (function loop2() {
        if (i == threads.length) {
          return setImmediate(loop1);
        }
        updateThread(threads[i++].id, (err) => {
          if (err) return done(err);
          setImmediate(loop2);
        });
      })();
    });
  })();
};

expb.core.get('/posts/search', function (req, res, done) {
  search(req, res, false, done);
});

expb.core.get('/api/posts/search', function (req, res, done) {
  search(req, res, true, done);
});

function search(req, res, api, done) {
  userb.checkUser(res, function (err, user) {
    if (err) return done(err);
    var q = req.query.q || '';
    var p = Math.max(parseInt(req.query.p) || 1, 1);
    var ps = Math.min(Math.max(parseInt(req.query.ps) || 16, 1), 128);
    var categoryIndex = user.categoryIndex;
    var threads = [];
    mysql2.query('select id, cid, cdate, title, writer, text from threadmerged where match(merged) against(? in boolean mode) order by id desc limit ?, ?', [q, (p-1)*ps, ps], (err, r) => {
      if (err) return done(err);
      r.forEach((thread) => {
        var category = categoryIndex[thread.cid];
        if (category) {
          thread.category = {
            id: category.id,
            name: category.name
          };
          thread.cdateStr = date2.dateTimeString(thread.cdate),
          threads.push(thread);
        }
      });
      if (api) {
        res.json({
          threads: threads
        });
      } else {
        res.render('post/post-search', {
          query: req.query.q || '',
          threads: threads,
          prev: p > 1 ? new url2.UrlMaker('/posts/search').add('q', query).add('p', p - 1, 1).done() : undefined,
          next: new url2.UrlMaker('/posts/search').add('q', q).add('p', p + 1).done()
        });
      }
    });
  });
}
<commit_msg>fix search query bug.<commit_after>'use strict';

const init = require('../base/init');
const error = require('../base/error');
const config = require('../base/config');
const date2 = require('../base/date2');
const url2 = require('../base/url2');
const mysql2 = require('../mysql/mysql2');
const expb = require('../express/express-base');
const userb = require('../user/user-base');
const postb = require('./post-base');
const postsr = exports;

postsr.updateThread = function (tid, done) {
  mysql2.queryOne('select * from thread where id = ?', tid, (err, thread) => {
    if (err) return done(err);
    thread.merged = thread.writer + ' ' + thread.title + ' ';
    mysql2.query('select * from post where tid = ?', tid, (err, r) => {
      if (err) return done(err);
        r.forEach((post) => {
        thread.merged += post.text + " " + post.writer + " ";
        if (!thread.text) {
          thread.text = post.text.slice(0, 255);
        }
      });
      mysql2.query(
        'delete from threadmerged where id = ?;' +
        'insert into threadmerged set ?',
        [tid, thread],
        done);
    });
  });
};

var updateThread = postsr.updateThread;

postsr.updateAll = function (done) {
  let offset = 0;
  let ps = 100;
  (function loop1() {
    mysql2.query('select id from thread order by id limit ?, ?', [offset, ps], (err, threads) => {
      if (err) return done(err);
      if (!threads.length) return done();
      if (postsr.updateAll.showProgress) {
        process.stdout.write(offset + ' ');
      }
      offset += ps;
      let i = 0;
      (function loop2() {
        if (i == threads.length) {
          return setImmediate(loop1);
        }
        updateThread(threads[i++].id, (err) => {
          if (err) return done(err);
          setImmediate(loop2);
        });
      })();
    });
  })();
};

expb.core.get('/posts/search', function (req, res, done) {
  search(req, res, false, done);
});

expb.core.get('/api/posts/search', function (req, res, done) {
  search(req, res, true, done);
});

function search(req, res, api, done) {
  userb.checkUser(res, function (err, user) {
    if (err) return done(err);
    var q = req.query.q || '';
    var p = Math.max(parseInt(req.query.p) || 1, 1);
    var ps = Math.min(Math.max(parseInt(req.query.ps) || 16, 1), 128);
    var categoryIndex = user.categoryIndex;
    var threads = [];
    mysql2.query('select id, cid, cdate, title, writer, text from threadmerged where match(merged) against(? in boolean mode) order by id desc limit ?, ?', [q, (p-1)*ps, ps], (err, r) => {
      if (err) return done(err);
      r.forEach((thread) => {
        var category = categoryIndex[thread.cid];
        if (category) {
          thread.category = {
            id: category.id,
            name: category.name
          };
          thread.cdateStr = date2.dateTimeString(thread.cdate),
          threads.push(thread);
        }
      });
      if (api) {
        res.json({
          threads: threads
        });
      } else {
        res.render('post/post-search', {
          query: req.query.q || '',
          threads: threads,
          prev: p > 1 ? new url2.UrlMaker('/posts/search').add('q', q).add('p', p - 1, 1).done() : undefined,
          next: new url2.UrlMaker('/posts/search').add('q', q).add('p', p + 1).done()
        });
      }
    });
  });
}
<|endoftext|>


<commit_before>var express     = require('express');
var router      = express.Router();
var fs          = require('fs');

router.route('/').

    //
    // Get all Units
    //
    get(function(req, res) {

        res.json(require('../data/unit-data'));

    });

module.exports = router;<commit_msg>Added id and filename fields to JSON return<commit_after>var express     = require('express');
var router      = express.Router();
var fs          = require('fs');

router.route('/').

    //
    // Get all Units
    //
    get(function(req, res) {

        var units = require('../data/unit-data');
        for (var i = 0; i < units.length; i++) {
            units[i].id = i;
            units[i].filename = units[i].name.replace(' ', '').replace('-', '').replace('.', '').toLowerCase();
        }

        res.json(units);

    });

module.exports = router;<|endoftext|>


<commit_before>require('./check-versions')()

process.env.NODE_ENV = 'production'

var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')

var spinner = ora('building for production...')
spinner.start()

rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err
  webpack(webpackConfig, function (err, stats) {
    spinner.stop()
    if (err) throw err
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }) + '\n\n')

    console.log(chalk.cyan('  Build complete.\n'))
    console.log(chalk.yellow(
      '  Tip: built files are meant to be served over an HTTP server.\n' +
      '  Opening index.html over file:// won\'t work.\n'
    ))
  })
})
<commit_msg>Delete build.js<commit_after><|endoftext|>