<commit_before>const OS = require("os");
const path = require("path");
const Profiler = require("./profiler");
const CompileError = require("./compileerror");
const CompilerSupplier = require("./compilerSupplier");
const expect = require("truffle-expect");
const find_contracts = require("truffle-contract-sources");
const Config = require("truffle-config");
const debug = require("debug")("compile"); // eslint-disable-line no-unused-vars

// Most basic of the compile commands. Takes a hash of sources, where
// the keys are file or module paths and the values are the bodies of
// the contracts. Does not evaulate dependencies that aren't already given.
//
// Default options:
// {
//   strict: false,
//   quiet: false,
//   logger: console
// }
const compile = function(sources, options, callback) {
  if (typeof options === "function") {
    callback = options;
    options = {};
  }

  if (options.logger === undefined) options.logger = console;

  const hasTargets =
    options.compilationTargets && options.compilationTargets.length;

  expect.options(options, ["contracts_directory", "compilers"]);

  expect.options(options.compilers, ["solc"]);

  options.compilers.solc.settings.evmVersion =
    options.compilers.solc.settings.evmVersion ||
    options.compilers.solc.evmVersion ||
    {};
  options.compilers.solc.settings.optimizer =
    options.compilers.solc.settings.optimizer ||
    options.compilers.solc.optimizer ||
    {};

  // Grandfather in old solc config
  if (options.solc) {
    options.compilers.solc.settings.evmVersion = options.solc.evmVersion;
    options.compilers.solc.settings.optimizer = options.solc.optimizer;
  }

  // Ensure sources have operating system independent paths
  // i.e., convert backslashes to forward slashes; things like C: are left intact.
  const operatingSystemIndependentSources = {};
  const operatingSystemIndependentTargets = {};
  const originalPathMappings = {};

  Object.keys(sources).forEach(function(source) {
    // Turn all backslashes into forward slashes
    var replacement = source.replace(/\\/g, "/");

    // Turn G:/.../ into /G/.../ for Windows
    if (replacement.length >= 2 && replacement[1] === ":") {
      replacement = "/" + replacement;
      replacement = replacement.replace(":", "");
    }

    // Save the result
    operatingSystemIndependentSources[replacement] = sources[source];

    // Just substitute replacement for original in target case. It's
    // a disposable subset of `sources`
    if (hasTargets && options.compilationTargets.includes(source)) {
      operatingSystemIndependentTargets[replacement] = sources[source];
    }

    // Map the replacement back to the original source path.
    originalPathMappings[replacement] = source;
  });

  const defaultSelectors = {
    "": ["legacyAST", "ast"],
    "*": [
      "abi",
      "evm.bytecode.object",
      "evm.bytecode.sourceMap",
      "evm.deployedBytecode.object",
      "evm.deployedBytecode.sourceMap",
      "userdoc",
      "devdoc"
    ]
  };

  // Specify compilation targets
  // Each target uses defaultSelectors, defaulting to single target `*` if targets are unspecified
  const outputSelection = {};
  const targets = operatingSystemIndependentTargets;
  const targetPaths = Object.keys(targets);

  targetPaths.length
    ? targetPaths.forEach(key => (outputSelection[key] = defaultSelectors))
    : (outputSelection["*"] = defaultSelectors);

  const solcStandardInput = {
    language: "Solidity",
    sources: {},
    settings: {
      evmVersion: options.compilers.solc.settings.evmVersion,
      optimizer: options.compilers.solc.settings.optimizer,
      outputSelection
    }
  };

  // Nothing to compile? Bail.
  if (Object.keys(sources).length === 0) {
    return callback(null, [], []);
  }

  Object.keys(operatingSystemIndependentSources).forEach(file_path => {
    solcStandardInput.sources[file_path] = {
      content: operatingSystemIndependentSources[file_path]
    };
  });

  // Load solc module only when compilation is actually required.
  const supplier = new CompilerSupplier(options.compilers.solc);

  supplier
    .load()
    .then(solc => {
      const result = solc.compile(JSON.stringify(solcStandardInput));

      const standardOutput = JSON.parse(result);

      let errors = standardOutput.errors || [];
      let warnings = [];

      if (options.strict !== true) {
        warnings = errors.filter(error => error.severity === "warning");

        errors = errors.filter(error => error.severity !== "warning");

        if (options.quiet !== true && warnings.length > 0) {
          options.logger.log(
            OS.EOL + "    > compilation warnings encountered:" + OS.EOL
          );
          options.logger.log(
            warnings.map(warning => warning.formattedMessage).join()
          );
        }
      }

      if (errors.length > 0) {
        options.logger.log("");
        return callback(
          new CompileError(
            standardOutput.errors.map(error => error.formattedMessage).join()
          )
        );
      }

      var contracts = standardOutput.contracts;

      var files = [];
      Object.keys(standardOutput.sources).forEach(filename => {
        var source = standardOutput.sources[filename];
        files[source.id] = originalPathMappings[filename];
      });

      var returnVal = {};

      // This block has comments in it as it's being prepared for solc > 0.4.10
      Object.keys(contracts).forEach(source_path => {
        var files_contracts = contracts[source_path];

        Object.keys(files_contracts).forEach(contract_name => {
          var contract = files_contracts[contract_name];

          // All source will have a key, but only the compiled source will have
          // the evm output.
          if (!Object.keys(contract.evm).length) return;

          var contract_definition = {
            contract_name: contract_name,
            sourcePath: originalPathMappings[source_path], // Save original source path, not modified ones
            source: operatingSystemIndependentSources[source_path],
            sourceMap: contract.evm.bytecode.sourceMap,
            deployedSourceMap: contract.evm.deployedBytecode.sourceMap,
            legacyAST: standardOutput.sources[source_path].legacyAST,
            ast: standardOutput.sources[source_path].ast,
            abi: contract.abi,
            bytecode: "0x" + contract.evm.bytecode.object,
            deployedBytecode: "0x" + contract.evm.deployedBytecode.object,
            unlinked_binary: "0x" + contract.evm.bytecode.object, // deprecated
            compiler: {
              name: "solc",
              version: solc.version()
            },
            devdoc: contract.devdoc,
            userdoc: contract.userdoc
          };

          // Reorder ABI so functions are listed in the order they appear
          // in the source file. Solidity tests need to execute in their expected sequence.
          contract_definition.abi = orderABI(contract_definition);

          // Go through the link references and replace them with older-style
          // identifiers. We'll do this until we're ready to making a breaking
          // change to this code.
          Object.keys(contract.evm.bytecode.linkReferences).forEach(function(
            file_name
          ) {
            var fileLinks = contract.evm.bytecode.linkReferences[file_name];

            Object.keys(fileLinks).forEach(function(library_name) {
              var linkReferences = fileLinks[library_name] || [];

              contract_definition.bytecode = replaceLinkReferences(
                contract_definition.bytecode,
                linkReferences,
                library_name
              );
              contract_definition.unlinked_binary = replaceLinkReferences(
                contract_definition.unlinked_binary,
                linkReferences,
                library_name
              );
            });
          });

          // Now for the deployed bytecode
          Object.keys(contract.evm.deployedBytecode.linkReferences).forEach(
            function(file_name) {
              var fileLinks =
                contract.evm.deployedBytecode.linkReferences[file_name];

              Object.keys(fileLinks).forEach(function(library_name) {
                var linkReferences = fileLinks[library_name] || [];

                contract_definition.deployedBytecode = replaceLinkReferences(
                  contract_definition.deployedBytecode,
                  linkReferences,
                  library_name
                );
              });
            }
          );

          returnVal[contract_name] = contract_definition;
        });
      });

      const compilerInfo = { name: "solc", version: solc.version() };

      callback(null, returnVal, files, compilerInfo);
    })
    .catch(callback);
};

function replaceLinkReferences(bytecode, linkReferences, libraryName) {
  var linkId = "__" + libraryName;

  while (linkId.length < 40) {
    linkId += "_";
  }

  linkReferences.forEach(function(ref) {
    // ref.start is a byte offset. Convert it to character offset.
    var start = ref.start * 2 + 2;

    bytecode =
      bytecode.substring(0, start) + linkId + bytecode.substring(start + 40);
  });

  return bytecode;
}

function orderABI(contract) {
  var contract_definition;
  var ordered_function_names = [];

  for (var i = 0; i < contract.legacyAST.children.length; i++) {
    var definition = contract.legacyAST.children[i];

    // AST can have multiple contract definitions, make sure we have the
    // one that matches our contract
    if (
      definition.name !== "ContractDefinition" ||
      definition.attributes.name !== contract.contract_name
    ) {
      continue;
    }

    contract_definition = definition;
    break;
  }

  if (!contract_definition) return contract.abi;
  if (!contract_definition.children) return contract.abi;

  contract_definition.children.forEach(function(child) {
    if (child.name === "FunctionDefinition") {
      ordered_function_names.push(child.attributes.name);
    }
  });

  // Put function names in a hash with their order, lowest first, for speed.
  var functions_to_remove = ordered_function_names.reduce(function(
    obj,
    value,
    index
  ) {
    obj[value] = index;
    return obj;
  },
  {});

  // Filter out functions from the abi
  var function_definitions = contract.abi.filter(function(item) {
    return functions_to_remove[item.name] !== undefined;
  });

  // Sort removed function defintions
  function_definitions = function_definitions.sort(function(item_a, item_b) {
    var a = functions_to_remove[item_a.name];
    var b = functions_to_remove[item_b.name];

    if (a > b) return 1;
    if (a < b) return -1;
    return 0;
  });

  // Create a new ABI, placing ordered functions at the end.
  var newABI = [];
  contract.abi.forEach(function(item) {
    if (functions_to_remove[item.name] !== undefined) return;
    newABI.push(item);
  });

  // Now pop the ordered functions definitions on to the end of the abi..
  Array.prototype.push.apply(newABI, function_definitions);

  return newABI;
}

// contracts_directory: String. Directory where .sol files can be found.
// quiet: Boolean. Suppress output. Defaults to false.
// strict: Boolean. Return compiler warnings as errors. Defaults to false.
compile.all = function(options, callback) {
  find_contracts(options.contracts_directory, function(err, files) {
    if (err) return callback(err);

    options.paths = files;
    compile.with_dependencies(options, callback);
  });
};

// contracts_directory: String. Directory where .sol files can be found.
// build_directory: String. Optional. Directory where .sol.js files can be found. Only required if `all` is false.
// all: Boolean. Compile all sources found. Defaults to true. If false, will compare sources against built files
//      in the build directory to see what needs to be compiled.
// quiet: Boolean. Suppress output. Defaults to false.
// strict: Boolean. Return compiler warnings as errors. Defaults to false.
compile.necessary = function(options, callback) {
  options.logger = options.logger || console;

  Profiler.updated(options, function(err, updated) {
    if (err) return callback(err);

    if (updated.length === 0 && options.quiet !== true) {
      return callback(null, [], {});
    }

    options.paths = updated;
    compile.with_dependencies(options, callback);
  });
};

compile.with_dependencies = function(options, callback) {
  var self = this;

  options.logger = options.logger || console;
  options.contracts_directory = options.contracts_directory || process.cwd();

  expect.options(options, [
    "paths",
    "working_directory",
    "contracts_directory",
    "resolver"
  ]);

  var config = Config.default().merge(options);

  Profiler.required_sources(
    config.with({
      paths: options.paths,
      base_path: options.contracts_directory,
      resolver: options.resolver
    }),
    (err, allSources, required) => {
      if (err) return callback(err);

      var hasTargets = required.length;

      hasTargets
        ? self.display(required, options)
        : self.display(allSources, options);

      options.compilationTargets = required;
      compile(allSources, options, callback);
    }
  );
};

compile.display = function(paths, options) {
  if (options.quiet !== true) {
    if (!Array.isArray(paths)) {
      paths = Object.keys(paths);
    }

    const blacklistRegex = /^truffle\//;

    paths.sort().forEach(contract => {
      if (path.isAbsolute(contract)) {
        contract =
          "." + path.sep + path.relative(options.working_directory, contract);
      }
      if (contract.match(blacklistRegex)) return;
      options.logger.log("> Compiling " + contract);
    });
  }
};

compile.CompilerSupplier = CompilerSupplier;
module.exports = compile;
<commit_msg>add metadata to solc input & output<commit_after>const OS = require("os");
const path = require("path");
const Profiler = require("./profiler");
const CompileError = require("./compileerror");
const CompilerSupplier = require("./compilerSupplier");
const expect = require("truffle-expect");
const find_contracts = require("truffle-contract-sources");
const Config = require("truffle-config");
const debug = require("debug")("compile"); // eslint-disable-line no-unused-vars

// Most basic of the compile commands. Takes a hash of sources, where
// the keys are file or module paths and the values are the bodies of
// the contracts. Does not evaulate dependencies that aren't already given.
//
// Default options:
// {
//   strict: false,
//   quiet: false,
//   logger: console
// }
const compile = function(sources, options, callback) {
  if (typeof options === "function") {
    callback = options;
    options = {};
  }

  if (options.logger === undefined) options.logger = console;

  const hasTargets =
    options.compilationTargets && options.compilationTargets.length;

  expect.options(options, ["contracts_directory", "compilers"]);

  expect.options(options.compilers, ["solc"]);

  options.compilers.solc.settings.evmVersion =
    options.compilers.solc.settings.evmVersion ||
    options.compilers.solc.evmVersion ||
    {};
  options.compilers.solc.settings.optimizer =
    options.compilers.solc.settings.optimizer ||
    options.compilers.solc.optimizer ||
    {};

  // Grandfather in old solc config
  if (options.solc) {
    options.compilers.solc.settings.evmVersion = options.solc.evmVersion;
    options.compilers.solc.settings.optimizer = options.solc.optimizer;
  }

  // Ensure sources have operating system independent paths
  // i.e., convert backslashes to forward slashes; things like C: are left intact.
  const operatingSystemIndependentSources = {};
  const operatingSystemIndependentTargets = {};
  const originalPathMappings = {};

  Object.keys(sources).forEach(function(source) {
    // Turn all backslashes into forward slashes
    var replacement = source.replace(/\\/g, "/");

    // Turn G:/.../ into /G/.../ for Windows
    if (replacement.length >= 2 && replacement[1] === ":") {
      replacement = "/" + replacement;
      replacement = replacement.replace(":", "");
    }

    // Save the result
    operatingSystemIndependentSources[replacement] = sources[source];

    // Just substitute replacement for original in target case. It's
    // a disposable subset of `sources`
    if (hasTargets && options.compilationTargets.includes(source)) {
      operatingSystemIndependentTargets[replacement] = sources[source];
    }

    // Map the replacement back to the original source path.
    originalPathMappings[replacement] = source;
  });

  const defaultSelectors = {
    "": ["legacyAST", "ast"],
    "*": [
      "abi",
      "metadata",
      "evm.bytecode.object",
      "evm.bytecode.sourceMap",
      "evm.deployedBytecode.object",
      "evm.deployedBytecode.sourceMap",
      "userdoc",
      "devdoc"
    ]
  };

  // Specify compilation targets
  // Each target uses defaultSelectors, defaulting to single target `*` if targets are unspecified
  const outputSelection = {};
  const targets = operatingSystemIndependentTargets;
  const targetPaths = Object.keys(targets);

  targetPaths.length
    ? targetPaths.forEach(key => (outputSelection[key] = defaultSelectors))
    : (outputSelection["*"] = defaultSelectors);

  const solcStandardInput = {
    language: "Solidity",
    sources: {},
    settings: {
      evmVersion: options.compilers.solc.settings.evmVersion,
      optimizer: options.compilers.solc.settings.optimizer,
      outputSelection
    }
  };

  // Nothing to compile? Bail.
  if (Object.keys(sources).length === 0) {
    return callback(null, [], []);
  }

  Object.keys(operatingSystemIndependentSources).forEach(file_path => {
    solcStandardInput.sources[file_path] = {
      content: operatingSystemIndependentSources[file_path]
    };
  });

  // Load solc module only when compilation is actually required.
  const supplier = new CompilerSupplier(options.compilers.solc);

  supplier
    .load()
    .then(solc => {
      const result = solc.compile(JSON.stringify(solcStandardInput));

      const standardOutput = JSON.parse(result);

      let errors = standardOutput.errors || [];
      let warnings = [];

      if (options.strict !== true) {
        warnings = errors.filter(error => error.severity === "warning");

        errors = errors.filter(error => error.severity !== "warning");

        if (options.quiet !== true && warnings.length > 0) {
          options.logger.log(
            OS.EOL + "    > compilation warnings encountered:" + OS.EOL
          );
          options.logger.log(
            warnings.map(warning => warning.formattedMessage).join()
          );
        }
      }

      if (errors.length > 0) {
        options.logger.log("");
        return callback(
          new CompileError(
            standardOutput.errors.map(error => error.formattedMessage).join()
          )
        );
      }

      var contracts = standardOutput.contracts;

      var files = [];
      Object.keys(standardOutput.sources).forEach(filename => {
        var source = standardOutput.sources[filename];
        files[source.id] = originalPathMappings[filename];
      });

      var returnVal = {};

      // This block has comments in it as it's being prepared for solc > 0.4.10
      Object.keys(contracts).forEach(source_path => {
        var files_contracts = contracts[source_path];

        Object.keys(files_contracts).forEach(contract_name => {
          var contract = files_contracts[contract_name];

          // All source will have a key, but only the compiled source will have
          // the evm output.
          if (!Object.keys(contract.evm).length) return;

          var contract_definition = {
            contract_name: contract_name,
            sourcePath: originalPathMappings[source_path], // Save original source path, not modified ones
            source: operatingSystemIndependentSources[source_path],
            sourceMap: contract.evm.bytecode.sourceMap,
            deployedSourceMap: contract.evm.deployedBytecode.sourceMap,
            legacyAST: standardOutput.sources[source_path].legacyAST,
            ast: standardOutput.sources[source_path].ast,
            abi: contract.abi,
            metadata: contract.metadata,
            bytecode: "0x" + contract.evm.bytecode.object,
            deployedBytecode: "0x" + contract.evm.deployedBytecode.object,
            unlinked_binary: "0x" + contract.evm.bytecode.object, // deprecated
            compiler: {
              name: "solc",
              version: solc.version()
            },
            devdoc: contract.devdoc,
            userdoc: contract.userdoc
          };

          // Reorder ABI so functions are listed in the order they appear
          // in the source file. Solidity tests need to execute in their expected sequence.
          contract_definition.abi = orderABI(contract_definition);

          // Go through the link references and replace them with older-style
          // identifiers. We'll do this until we're ready to making a breaking
          // change to this code.
          Object.keys(contract.evm.bytecode.linkReferences).forEach(function(
            file_name
          ) {
            var fileLinks = contract.evm.bytecode.linkReferences[file_name];

            Object.keys(fileLinks).forEach(function(library_name) {
              var linkReferences = fileLinks[library_name] || [];

              contract_definition.bytecode = replaceLinkReferences(
                contract_definition.bytecode,
                linkReferences,
                library_name
              );
              contract_definition.unlinked_binary = replaceLinkReferences(
                contract_definition.unlinked_binary,
                linkReferences,
                library_name
              );
            });
          });

          // Now for the deployed bytecode
          Object.keys(contract.evm.deployedBytecode.linkReferences).forEach(
            function(file_name) {
              var fileLinks =
                contract.evm.deployedBytecode.linkReferences[file_name];

              Object.keys(fileLinks).forEach(function(library_name) {
                var linkReferences = fileLinks[library_name] || [];

                contract_definition.deployedBytecode = replaceLinkReferences(
                  contract_definition.deployedBytecode,
                  linkReferences,
                  library_name
                );
              });
            }
          );

          returnVal[contract_name] = contract_definition;
        });
      });

      const compilerInfo = { name: "solc", version: solc.version() };

      callback(null, returnVal, files, compilerInfo);
    })
    .catch(callback);
};

function replaceLinkReferences(bytecode, linkReferences, libraryName) {
  var linkId = "__" + libraryName;

  while (linkId.length < 40) {
    linkId += "_";
  }

  linkReferences.forEach(function(ref) {
    // ref.start is a byte offset. Convert it to character offset.
    var start = ref.start * 2 + 2;

    bytecode =
      bytecode.substring(0, start) + linkId + bytecode.substring(start + 40);
  });

  return bytecode;
}

function orderABI(contract) {
  var contract_definition;
  var ordered_function_names = [];

  for (var i = 0; i < contract.legacyAST.children.length; i++) {
    var definition = contract.legacyAST.children[i];

    // AST can have multiple contract definitions, make sure we have the
    // one that matches our contract
    if (
      definition.name !== "ContractDefinition" ||
      definition.attributes.name !== contract.contract_name
    ) {
      continue;
    }

    contract_definition = definition;
    break;
  }

  if (!contract_definition) return contract.abi;
  if (!contract_definition.children) return contract.abi;

  contract_definition.children.forEach(function(child) {
    if (child.name === "FunctionDefinition") {
      ordered_function_names.push(child.attributes.name);
    }
  });

  // Put function names in a hash with their order, lowest first, for speed.
  var functions_to_remove = ordered_function_names.reduce(function(
    obj,
    value,
    index
  ) {
    obj[value] = index;
    return obj;
  },
  {});

  // Filter out functions from the abi
  var function_definitions = contract.abi.filter(function(item) {
    return functions_to_remove[item.name] !== undefined;
  });

  // Sort removed function defintions
  function_definitions = function_definitions.sort(function(item_a, item_b) {
    var a = functions_to_remove[item_a.name];
    var b = functions_to_remove[item_b.name];

    if (a > b) return 1;
    if (a < b) return -1;
    return 0;
  });

  // Create a new ABI, placing ordered functions at the end.
  var newABI = [];
  contract.abi.forEach(function(item) {
    if (functions_to_remove[item.name] !== undefined) return;
    newABI.push(item);
  });

  // Now pop the ordered functions definitions on to the end of the abi..
  Array.prototype.push.apply(newABI, function_definitions);

  return newABI;
}

// contracts_directory: String. Directory where .sol files can be found.
// quiet: Boolean. Suppress output. Defaults to false.
// strict: Boolean. Return compiler warnings as errors. Defaults to false.
compile.all = function(options, callback) {
  find_contracts(options.contracts_directory, function(err, files) {
    if (err) return callback(err);

    options.paths = files;
    compile.with_dependencies(options, callback);
  });
};

// contracts_directory: String. Directory where .sol files can be found.
// build_directory: String. Optional. Directory where .sol.js files can be found. Only required if `all` is false.
// all: Boolean. Compile all sources found. Defaults to true. If false, will compare sources against built files
//      in the build directory to see what needs to be compiled.
// quiet: Boolean. Suppress output. Defaults to false.
// strict: Boolean. Return compiler warnings as errors. Defaults to false.
compile.necessary = function(options, callback) {
  options.logger = options.logger || console;

  Profiler.updated(options, function(err, updated) {
    if (err) return callback(err);

    if (updated.length === 0 && options.quiet !== true) {
      return callback(null, [], {});
    }

    options.paths = updated;
    compile.with_dependencies(options, callback);
  });
};

compile.with_dependencies = function(options, callback) {
  var self = this;

  options.logger = options.logger || console;
  options.contracts_directory = options.contracts_directory || process.cwd();

  expect.options(options, [
    "paths",
    "working_directory",
    "contracts_directory",
    "resolver"
  ]);

  var config = Config.default().merge(options);

  Profiler.required_sources(
    config.with({
      paths: options.paths,
      base_path: options.contracts_directory,
      resolver: options.resolver
    }),
    (err, allSources, required) => {
      if (err) return callback(err);

      var hasTargets = required.length;

      hasTargets
        ? self.display(required, options)
        : self.display(allSources, options);

      options.compilationTargets = required;
      compile(allSources, options, callback);
    }
  );
};

compile.display = function(paths, options) {
  if (options.quiet !== true) {
    if (!Array.isArray(paths)) {
      paths = Object.keys(paths);
    }

    const blacklistRegex = /^truffle\//;

    paths.sort().forEach(contract => {
      if (path.isAbsolute(contract)) {
        contract =
          "." + path.sep + path.relative(options.working_directory, contract);
      }
      if (contract.match(blacklistRegex)) return;
      options.logger.log("> Compiling " + contract);
    });
  }
};

compile.CompilerSupplier = CompilerSupplier;
module.exports = compile;
<|endoftext|>


<commit_before>/*
 * This file is part of the Spludo Framework.
 * Copyright (c) 2009-2010 DracoBlue, http://dracoblue.net/
 *
 * Licensed under the terms of MIT License. For the full copyright and license
 * information, please see the LICENSE file in the root folder.
 */

var sys = require("sys");
var fs = require("fs");
var child_process = require("child_process");
var path = require("path");

require("./../core/util");

var working_directory = process.cwd() + '/';
var spludo_directory = path.dirname(__dirname) + '/';

SpludoGenerator = {};

SpludoGenerator.code_templates = {};

SpludoGenerator.target_directory = working_directory;
SpludoGenerator.working_directory = working_directory;

SpludoGenerator.addCodeTemplate = function(name, options) {
    options.name = name;
    SpludoGenerator.code_templates[name] = options;
};

SpludoGenerator.handleCodeTemplate = function(name) {
    var self = this;

    var code_template = this.code_templates[name];
    var parameters = code_template.parameters;
    var parameters_length = parameters.length;

    var values_chain = [];
    var values = [];

    return function(cb) {
        for (var i = 0; i < parameters_length; i++) {
            (function(parameter) {
                var validate_paramter_handler = function(chain_cb) {

                    var default_value = "";
                    var value = "";

                    chain(function(sub_chain_cb) {
                        code_template.getParameterDefault(parameter.name)(function(err, parameter_default_value) {
                            if (err) {
                                default_value = "";
                            } else {
                                default_value = parameter_default_value;
                            }
                            sub_chain_cb();
                        });
                    }, function(sub_chain_cb) {
                        sys.print(parameter.caption);

                        if (default_value !== "") {
                            sys.print(" [" + default_value + "]");
                        }

                        sys.print(': ');
                        var st = process.openStdin();

                        var data_handler = function(input_value) {
                            st.removeListener("data", data_handler);
                            value = input_value.toString().split("\n")[0];
                            sub_chain_cb();
                        };
                        st.addListener("data", data_handler);
                    }, function() {
                        if (value === "") {
                            value = default_value;
                        }

                        code_template.validateParameter(parameter.name, value)(function(err, valid_value) {
                            if (err) {
                                validate_paramter_handler(chain_cb);
                            } else {
                                values.push([parameter.name, valid_value]);
                                chain_cb();
                            }
                        });
                    });

                };

                values_chain.push(validate_paramter_handler);
            })(parameters[i]);
        }

        values_chain.push(function() {
            sys.puts("  ");
            sys.puts("   Working ... ");
            sys.puts("");

            if (typeof code_template.preExecuteHook !== "undefined") {
                code_template.preExecuteHook(values)(function() {
                    self.performCodeTemplate(__dirname + '/code-templates/' + code_template.name + '/', values)(function() {
                        if (typeof code_template.postExecuteHook !== "undefined") {
                            code_template.postExecuteHook(values)(function() {
                                cb();
                            });
                        } else {
                            cb();
                        }
                    });
                });
            } else {
                self.performCodeTemplate(__dirname + '/code-templates/' + code_template.name + '/', values)(function() {
                    if (typeof code_template.postExecuteHook !== "undefined") {
                        code_template.postExecuteHook(values)(function() {
                            cb();
                        });
                    } else {
                        cb();
                    }
                });
            }

        });

        chain.apply(GLOBAL, values_chain);
    };
};

SpludoGenerator.performCodeTemplate = function(template_directory, values) {
    var self = this;

    var values_length = values.length;

    var token_replacer = function(input) {
        var output = input;

        for (var i = 0; i < values_length; i++) {
            output = output.split("%%%" + values[i][0] + "%%%").join(values[i][1]);
        }

        return output;
    };

    var files = [];

    return function(cb) {

        chain(function(chain_cb) {
            child_process.exec("cd " + template_directory + " && find .", function(err, raw_files) {
                if (err) {
                    sys.puts("Could not list code-template from: " + template_directory);
                    process.exit(1);
                } else {
                    var raw_files = raw_files.split("\n");
                    var raw_files_length = raw_files.length;
                    for (var i = 0; i < raw_files_length; i++) {
                        var file = raw_files[i].substr(2);
                        if (file !== '') {
                            files.push(file);
                        }
                    }
                }
                chain_cb();
            });
        }, function() {
            var files_length = files.length;
            for (var i = 0; i < files_length; i++) {
                var file = files[i];
                var file_stat = fs.statSync(template_directory + file);

                if (file_stat.isDirectory()) {
                    fs.mkdirSync(self.target_directory + token_replacer(file), 0755);
                    sys.puts("Created folder: " + self.target_directory + token_replacer(file));
                } else {
                    if (path.extname(file) === '.jpg' || path.extname(file) === '.png') {
                        var raw_file_contents = fs.readFileSync(template_directory + file, 'binary').toString();
                        fs.writeFileSync(self.target_directory + token_replacer(file), raw_file_contents, 'binary');
                        sys.puts("Created (binary) file: " + self.target_directory + token_replacer(file));
                    } else {
                        var raw_file_contents = fs.readFileSync(template_directory + file).toString();
                        fs.writeFileSync(self.target_directory + token_replacer(file), token_replacer(raw_file_contents));
                        sys.puts("Created file: " + self.target_directory + token_replacer(file));
                    }
                }
            }

            sys.puts("  ");
            sys.puts("   Finished!");
            sys.puts("");

            cb();
        });
    };
};

require("./code-templates/core-code-templates");

var code_template = process.ARGV[2];

sys.puts("  ");
sys.puts(" Spludo-Generator - http://spludo.com/ - Copyright 2009-2010 by DracoBlue <http://dracoblue.net>");
sys.puts("  ");

if (!code_template || code_template === "help") {
    for (var name in SpludoGenerator.code_templates) {
        sys.puts("    spludo/spludo-gen " + name);
        sys.puts("      " + SpludoGenerator.code_templates[name].description);
        sys.puts(" ");
    }
    process.exit(0);
}

sys.puts("   Template: " + code_template);
sys.puts("");

if (typeof SpludoGenerator.code_templates[code_template] === "undefined") {
    sys.puts("   Error: Unsupported code template: " + code_template);
    process.exit(1);
}

SpludoGenerator.handleCodeTemplate(code_template)(function() {
    process.exit(0);
});
<commit_msg>Do now assume that spludo-gen is in the path.<commit_after>/*
 * This file is part of the Spludo Framework.
 * Copyright (c) 2009-2010 DracoBlue, http://dracoblue.net/
 *
 * Licensed under the terms of MIT License. For the full copyright and license
 * information, please see the LICENSE file in the root folder.
 */

var sys = require("sys");
var fs = require("fs");
var child_process = require("child_process");
var path = require("path");

require("./../core/util");

var working_directory = process.cwd() + '/';
var spludo_directory = path.dirname(__dirname) + '/';

SpludoGenerator = {};

SpludoGenerator.code_templates = {};

SpludoGenerator.target_directory = working_directory;
SpludoGenerator.working_directory = working_directory;

SpludoGenerator.addCodeTemplate = function(name, options) {
    options.name = name;
    SpludoGenerator.code_templates[name] = options;
};

SpludoGenerator.handleCodeTemplate = function(name) {
    var self = this;

    var code_template = this.code_templates[name];
    var parameters = code_template.parameters;
    var parameters_length = parameters.length;

    var values_chain = [];
    var values = [];

    return function(cb) {
        for (var i = 0; i < parameters_length; i++) {
            (function(parameter) {
                var validate_paramter_handler = function(chain_cb) {

                    var default_value = "";
                    var value = "";

                    chain(function(sub_chain_cb) {
                        code_template.getParameterDefault(parameter.name)(function(err, parameter_default_value) {
                            if (err) {
                                default_value = "";
                            } else {
                                default_value = parameter_default_value;
                            }
                            sub_chain_cb();
                        });
                    }, function(sub_chain_cb) {
                        sys.print(parameter.caption);

                        if (default_value !== "") {
                            sys.print(" [" + default_value + "]");
                        }

                        sys.print(': ');
                        var st = process.openStdin();

                        var data_handler = function(input_value) {
                            st.removeListener("data", data_handler);
                            value = input_value.toString().split("\n")[0];
                            sub_chain_cb();
                        };
                        st.addListener("data", data_handler);
                    }, function() {
                        if (value === "") {
                            value = default_value;
                        }

                        code_template.validateParameter(parameter.name, value)(function(err, valid_value) {
                            if (err) {
                                validate_paramter_handler(chain_cb);
                            } else {
                                values.push([parameter.name, valid_value]);
                                chain_cb();
                            }
                        });
                    });

                };

                values_chain.push(validate_paramter_handler);
            })(parameters[i]);
        }

        values_chain.push(function() {
            sys.puts("  ");
            sys.puts("   Working ... ");
            sys.puts("");

            if (typeof code_template.preExecuteHook !== "undefined") {
                code_template.preExecuteHook(values)(function() {
                    self.performCodeTemplate(__dirname + '/code-templates/' + code_template.name + '/', values)(function() {
                        if (typeof code_template.postExecuteHook !== "undefined") {
                            code_template.postExecuteHook(values)(function() {
                                cb();
                            });
                        } else {
                            cb();
                        }
                    });
                });
            } else {
                self.performCodeTemplate(__dirname + '/code-templates/' + code_template.name + '/', values)(function() {
                    if (typeof code_template.postExecuteHook !== "undefined") {
                        code_template.postExecuteHook(values)(function() {
                            cb();
                        });
                    } else {
                        cb();
                    }
                });
            }

        });

        chain.apply(GLOBAL, values_chain);
    };
};

SpludoGenerator.performCodeTemplate = function(template_directory, values) {
    var self = this;

    var values_length = values.length;

    var token_replacer = function(input) {
        var output = input;

        for (var i = 0; i < values_length; i++) {
            output = output.split("%%%" + values[i][0] + "%%%").join(values[i][1]);
        }

        return output;
    };

    var files = [];

    return function(cb) {

        chain(function(chain_cb) {
            child_process.exec("cd " + template_directory + " && find .", function(err, raw_files) {
                if (err) {
                    sys.puts("Could not list code-template from: " + template_directory);
                    process.exit(1);
                } else {
                    var raw_files = raw_files.split("\n");
                    var raw_files_length = raw_files.length;
                    for (var i = 0; i < raw_files_length; i++) {
                        var file = raw_files[i].substr(2);
                        if (file !== '') {
                            files.push(file);
                        }
                    }
                }
                chain_cb();
            });
        }, function() {
            var files_length = files.length;
            for (var i = 0; i < files_length; i++) {
                var file = files[i];
                var file_stat = fs.statSync(template_directory + file);

                if (file_stat.isDirectory()) {
                    fs.mkdirSync(self.target_directory + token_replacer(file), 0755);
                    sys.puts("Created folder: " + self.target_directory + token_replacer(file));
                } else {
                    if (path.extname(file) === '.jpg' || path.extname(file) === '.png') {
                        var raw_file_contents = fs.readFileSync(template_directory + file, 'binary').toString();
                        fs.writeFileSync(self.target_directory + token_replacer(file), raw_file_contents, 'binary');
                        sys.puts("Created (binary) file: " + self.target_directory + token_replacer(file));
                    } else {
                        var raw_file_contents = fs.readFileSync(template_directory + file).toString();
                        fs.writeFileSync(self.target_directory + token_replacer(file), token_replacer(raw_file_contents));
                        sys.puts("Created file: " + self.target_directory + token_replacer(file));
                    }
                }
            }

            sys.puts("  ");
            sys.puts("   Finished!");
            sys.puts("");

            cb();
        });
    };
};

require("./code-templates/core-code-templates");

var code_template = process.ARGV[2];

sys.puts("  ");
sys.puts(" Spludo-Generator - http://spludo.com/ - Copyright 2009-2010 by DracoBlue <http://dracoblue.net>");
sys.puts("  ");

if (!code_template || code_template === "help") {
    for (var name in SpludoGenerator.code_templates) {
        sys.puts("    $ spludo-gen " + name);
        sys.puts("      " + SpludoGenerator.code_templates[name].description);
        sys.puts(" ");
    }
    process.exit(0);
}

sys.puts("   Template: " + code_template);
sys.puts("");

if (typeof SpludoGenerator.code_templates[code_template] === "undefined") {
    sys.puts("   Error: Unsupported code template: " + code_template);
    process.exit(1);
}

SpludoGenerator.handleCodeTemplate(code_template)(function() {
    process.exit(0);
});
<|endoftext|>


<commit_before>(function($) {

$.widget('ui.dmZone', {

  _init : function()
  {
    var self = this;

    self.initialize();
  },

  initialize: function()
  {
    this.id = this.element.attr('id').substring(8);

    this.initWidgets();

    this.initEdit();
  },

  initEdit: function()
  {
    var zone = this;

    $('a.dm_zone_edit', this.element).bind('click', function() {
      if (zone.element.hasClass('dm_dragging')) {
        return false;
      }
      zone.openEditDialog();
    });
  },

	openEditDialog: function()
	{
    var zone = this, dialog_class = zone.element.attr('id')+'_edit_dialog';

    if ($('div.'+dialog_class).length)
    {
      return;
    }

    var $dialog = $.dm.ctrl.ajaxDialog({
      url:      $.dm.ctrl.getHref('+/dmZone/edit'),
      data:     { zone_id: zone.getId() },
      title:    $('#dm_zone_'+zone.getId()+' > a.dm_zone_edit').attr('title'),
			'class':  dialog_class,
      beforeClose:  function() {
        if (zone.deleted) return;
        setTimeout(function() {
          $.ajax({
						dataType: 'json',
            url:      $.dm.ctrl.getHref('+/dmZone/getAttributes'),
            data:     { zone_id: zone.getId() },
            success:  function(datas) {
              zone.element.attr('class', 'dm_zone '+ (datas[1] || "").replace(/\./g, ' ')).css('width', datas[0]);
            }
          });
        }, 100);
      }
    }).bind('dmAjaxResponse', function() {
      $dialog.prepare();
      /*
       * Apply generic front form abilities
       */
      $dialog.dmFrontForm();
      var $form = $('form', $dialog).dmAjaxForm({
        beforeSubmit: function() {
          $dialog.block();
          zone.element.block();
        },
        success:  function(html) {
          if (html == 'ok') {
            $dialog.dialog('close');
          }
          $dialog.html(html).trigger('dmAjaxResponse');
          if(!$('ul.error_list', $form).length) {
            zone.element.attr('class', 'dm_zone '+ $('input.dm_zone_css_class', $form).val().replace(/\./g, ' ')).css('width', $('input.dm_zone_width', $form).val());
          }
          zone.element.unblock();
        }
      });

      $('a.delete', $form).click(function() {
        if (confirm($(this).attr('title')+" ?")) {
          zone._delete();
          $dialog.dialog('close');
        }
      });
    });
	},

  initWidgets: function()
  {
    this.$widgets = $('div.dm_widget', this.element);

    if (this.$widgets.length)
    {
      this.$widgets.dmWidget();
    }

    $('div.dm_widgets', this.element).sortable({
      opacity:                0.5,
      handle:                 'a.dm_widget_edit',
      distance:               5,
      placeholder:            'dm_widget_placeholder',
      revert:                 false,
      scroll:                 true,
      connectWith:            'div.dm_widgets',
      forceHelperSize:        false,
      forcePlaceholderSize:   false,
      tolerance:              'intersect',
      receive:                function(e, ui) { sortEvents.receive = $(this).parent(); },
      remove:                 function(e, ui) { sortEvents.remove = true; },
      update:                 function(e, ui) { sortEvents.update = true; },
      start:                  function(e, ui)
      {
        ui.item.addClass('dm_dragging');

        // adding a widget
        if (ui.placeholder.is('span'))
        {
          ui.placeholder
          .addClass('dm dm_widget block')
          .html('
New Widget
');
        }
        // moving a widget
        else
        {
          ui.placeholder.addClass(ui.item.attr('class')).css('width', ui.item.css('width')).html(ui.item.html());
				}

        $('#dm_page div.dm_widgets').addClass('droppable-active');

        sortEvents = [];
      },
      stop:                   function(e, ui)
      {
        if (sortEvents.update && sortEvents.receive && sortEvents.remove)
        {
          sortEvents.receive.dmZone('moveWidget', ui.item);
        }
        else if (sortEvents.update && sortEvents.receive)
        {
          $(this).parent().dmZone(ui.item.hasClass('widget_paste') ? 'pasteWidget' : 'addWidget', ui.item);
        }
        else if (sortEvents.update)
        {
          $(this).parent().dmZone('sortWidgets');
        }
        setTimeout(function() { ui.item.removeClass('dm_dragging'); }, 200);

        $('#dm_page div.dm_widgets').removeClass('droppable-active');
      }
    });
  },

  moveWidget: function($widget)
  {
    $.ajax({
      url:      $.dm.ctrl.getHref('+/dmWidget/move')
      +"?moved_dm_widget="+$widget.dmWidget('getId')
      +"&to_dm_zone="+this.getId()
      +"&"+$('div.dm_widgets', this.element).sortable('serialize')
    });
  },

  addWidget: function($widget)
  {
    var zone = this, mod_act = $widget.attr('id').replace(/dmwa\_/, '').split(/-/);

    $.ajax({
      url:      $.dm.ctrl.getHref('+/dmWidget/add')+"?to_dm_zone="+zone.getId(),
      data: {
        mod:    mod_act[0],
        act:    mod_act[1]
			},
      success:  function(widgetHtml) {
        $('div.dm_widgets', zone.element).find('span.widget_add').replaceWith(widgetHtml);
        var $newWidget = null;
				$('div.dm_widget', zone.element).each(function() {
					if (!$(this).data('loaded'))
					{
						$newWidget = $(this);
					}
				});
        zone.initialize();
        zone.sortWidgets();
        $newWidget.dmWidget('openEditDialog');
      }
    });
  },

  pasteWidget: function($widget)
  {
    var zone = this, id = $widget.attr('id').replace(/dmwp\_/, '');

    // if widget was cutted then pasted on the same page,
    // remove the cutted widget
    if($widget.hasClass('dm_cut') && ($cutted = $('#dm_widget_'+id)))
    {
      $cutted.remove();
    }

    $.ajax({
      url:      $.dm.ctrl.getHref('+/dmWidget/paste')+"?to_dm_zone="+zone.getId(),
      data: {
        id:     id
			},
      success:  function(widgetHtml)
      {
        $('div.dm_widgets', zone.element).find('span.widget_paste').replaceWith(widgetHtml);
        zone.initialize();
        zone.sortWidgets();
        $('#dm_tool_bar').dmFrontToolBar('reloadAddMenu');
      }
    });
  },

  sortWidgets: function()
  {
    $.ajax({
      url:      $.dm.ctrl.getHref('+/dmWidget/sort')+"?dm_zone="+this.getId()+"&"+$('div.dm_widgets', this.element).sortable('serialize')
    });
  },

  _delete: function()
  {
    var zone = this;

    this.deleted = true;

    $.ajax({
      url:      $.dm.ctrl.getHref('+/dmZone/delete'),
      data:     { zone_id: this.getId() }
    });

    this.element.slideUp(500, function() { zone.destroy(); zone.element.remove(); });
  },

  getId: function()
  {
    return this.id;
  },

  getWidgets: function()
  {
    return this.$widgets;
  }

});

})(jQuery);<commit_msg>[Diem] - simplified dmZone.js<commit_after>(function($) {

$.widget('ui.dmZone', {

  _init : function()
  {
    this.initialize();
  },

  initialize: function()
  {
    var self = this;

    self.id = self.element.attr('id').substring(8);

    self.initWidgets();

    $('a.dm_zone_edit', self.element).bind('click', function()
    {
      if (!self.element.hasClass('dm_dragging'))
      {
        self.openEditDialog();
      }
    });
  },

	openEditDialog: function()
	{
    var zone = this, dialog_class = zone.element.attr('id')+'_edit_dialog';

    if ($('div.'+dialog_class).length)
    {
      return;
    }

    var $dialog = $.dm.ctrl.ajaxDialog({
      url:      $.dm.ctrl.getHref('+/dmZone/edit'),
      data:     { zone_id: zone.getId() },
      title:    $('#dm_zone_'+zone.getId()+' > a.dm_zone_edit').attr('title'),
			'class':  dialog_class,
      beforeClose:  function()
      {
        if (zone.deleted) return;
        setTimeout(function() {
          $.ajax({
						dataType: 'json',
            url:      $.dm.ctrl.getHref('+/dmZone/getAttributes'),
            data:     { zone_id: zone.getId() },
            success:  function(datas) {
              zone.element.attr('class', 'dm_zone '+ (datas[1] || "").replace(/\./g, ' ')).css('width', datas[0]);
            }
          });
        }, 100);
      }
    }).bind('dmAjaxResponse', function()
    {
      $dialog.prepare();
      /*
       * Apply generic front form abilities
       */
      $dialog.dmFrontForm();
      var $form = $('form', $dialog).dmAjaxForm({
        beforeSubmit: function() {
          $dialog.block();
          zone.element.block();
        },
        success:  function(html) {
          if (html == 'ok') {
            $dialog.dialog('close');
          }
          $dialog.html(html).trigger('dmAjaxResponse');
          if(!$('ul.error_list', $form).length) {
            zone.element.attr('class', 'dm_zone '+ $('input.dm_zone_css_class', $form).val().replace(/\./g, ' ')).css('width', $('input.dm_zone_width', $form).val());
          }
          zone.element.unblock();
        }
      });

      $('a.delete', $form).click(function() {
        if (confirm($(this).attr('title')+" ?")) {
          zone._delete();
          $dialog.dialog('close');
        }
      });
    });
	},

  initWidgets: function()
  {
    this.$widgets = $('div.dm_widget', this.element);

    if (this.$widgets.length)
    {
      this.$widgets.dmWidget();
    }

    $('div.dm_widgets', this.element).sortable({
      opacity:                0.5,
      handle:                 'a.dm_widget_edit',
      distance:               5,
      placeholder:            'dm_widget_placeholder',
      revert:                 false,
      scroll:                 true,
      connectWith:            'div.dm_widgets',
      forceHelperSize:        false,
      forcePlaceholderSize:   false,
      tolerance:              'intersect',
      receive:                function(e, ui) { sortEvents.receive = $(this).parent(); },
      remove:                 function(e, ui) { sortEvents.remove = true; },
      update:                 function(e, ui) { sortEvents.update = true; },
      start:                  function(e, ui)
      {
        ui.item.addClass('dm_dragging');

        // adding a widget
        if (ui.placeholder.is('span'))
        {
          ui.placeholder
          .addClass('dm dm_widget block')
          .html('
New Widget
');
        }
        // moving a widget
        else
        {
          ui.placeholder.addClass(ui.item.attr('class')).css('width', ui.item.css('width')).html(ui.item.html());
				}

        $('#dm_page div.dm_widgets').addClass('droppable-active');

        sortEvents = [];
      },
      stop:                   function(e, ui)
      {
        if (sortEvents.update && sortEvents.receive && sortEvents.remove)
        {
          sortEvents.receive.dmZone('moveWidget', ui.item);
        }
        else if (sortEvents.update && sortEvents.receive)
        {
          $(this).parent().dmZone(ui.item.hasClass('widget_paste') ? 'pasteWidget' : 'addWidget', ui.item);
        }
        else if (sortEvents.update)
        {
          $(this).parent().dmZone('sortWidgets');
        }
        setTimeout(function() { ui.item.removeClass('dm_dragging'); }, 200);

        $('#dm_page div.dm_widgets').removeClass('droppable-active');
      }
    });
  },

  moveWidget: function($widget)
  {
    $.ajax({
      url:      $.dm.ctrl.getHref('+/dmWidget/move')
      +"?moved_dm_widget="+$widget.dmWidget('getId')
      +"&to_dm_zone="+this.getId()
      +"&"+$('div.dm_widgets', this.element).sortable('serialize')
    });
  },

  addWidget: function($widget)
  {
    var zone = this, mod_act = $widget.attr('id').replace(/dmwa\_/, '').split(/-/);

    $.ajax({
      url:      $.dm.ctrl.getHref('+/dmWidget/add')+"?to_dm_zone="+zone.getId(),
      data: {
        mod:    mod_act[0],
        act:    mod_act[1]
			},
      success:  function(widgetHtml) {
        $('div.dm_widgets', zone.element).find('span.widget_add').replaceWith(widgetHtml);
        var $newWidget = null;
				$('div.dm_widget', zone.element).each(function() {
					if (!$(this).data('loaded'))
					{
						$newWidget = $(this);
					}
				});
        zone.initialize();
        zone.sortWidgets();
        $newWidget.dmWidget('openEditDialog');
      }
    });
  },

  pasteWidget: function($widget)
  {
    var zone = this, id = $widget.attr('id').replace(/dmwp\_/, '');

    // if widget was cutted then pasted on the same page,
    // remove the cutted widget
    if($widget.hasClass('dm_cut') && ($cutted = $('#dm_widget_'+id)))
    {
      $cutted.remove();
    }

    $.ajax({
      url:      $.dm.ctrl.getHref('+/dmWidget/paste')+"?to_dm_zone="+zone.getId(),
      data: {
        id:     id
			},
      success:  function(widgetHtml)
      {
        $('div.dm_widgets', zone.element).find('span.widget_paste').replaceWith(widgetHtml);
        zone.initialize();
        zone.sortWidgets();
        $('#dm_tool_bar').dmFrontToolBar('reloadAddMenu');
      }
    });
  },

  sortWidgets: function()
  {
    $.ajax({
      url:      $.dm.ctrl.getHref('+/dmWidget/sort')+"?dm_zone="+this.getId()+"&"+$('div.dm_widgets', this.element).sortable('serialize')
    });
  },

  _delete: function()
  {
    var zone = this;

    this.deleted = true;

    $.ajax({
      url:      $.dm.ctrl.getHref('+/dmZone/delete'),
      data:     { zone_id: this.getId() }
    });

    this.element.slideUp(500, function() { zone.destroy(); zone.element.remove(); });
  },

  getId: function()
  {
    return this.id;
  },

  getWidgets: function()
  {
    return this.$widgets;
  }

});

})(jQuery);<|endoftext|>


<commit_before>(function () {
    CompletedChallengesController.$inject = ['Challenges', 'Resources', 'ProfileService', 'Utils'];

    angular
        .module('myApp.components.completedChallenges', [])
        .component('kudosChallengeCompleted', {
            templateUrl: 'app/components/kudos-challenge-completed/kudos-challenge-completed.html',
            controller: ('CompletedChallengesController',CompletedChallengesController),
            controllerAs: 'chCompleted'
        });

    function CompletedChallengesController(Challenges, Resources, ProfileService, Utils) {
        var vm = this,
            showMoreLimit = 5;

        vm.completedChallengesLimit = 5;
        vm.completedChallengesCollection = [];
        vm.showList = false;

        vm.acornPlural = Utils.acornPlural;
        vm.getWinner = getWinner;
        vm.showMore = showMore;
        vm.showLess = showLess;
        vm.showMoreButton = showMoreButton;

        vm.$onInit = onInit();

        function onInit() {
            Challenges.getCompletedChallenges().then(function (val) {
                Resources.setCompletedChallenges(val);
                vm.completedChallengesCollection = Resources.getCompletedChallenges();
                showMoreButton(val);
            });

            if(!Resources.getCurrentUserEmail()){
                ProfileService.userHome().then(function (val) {
                    Resources.setCurrentUserEmail(val.email);
                    vm.userEmail = Resources.getCurrentUserEmail();
                });
            } else {
                vm.userEmail = Resources.getCurrentUserEmail();
            }
        }

        function getWinner(index) {
            if (Resources.getCompletedChallenges()[index].creatorStatus) {
                if (Resources.getCompletedChallenges()[index].creatorEmail == Resources.getCurrentUserEmail()) return "You won the challenge!";
                else return Resources.getCompletedChallenges()[index].creatorEmail + " won the challenge";
            } else if (!Resources.getCompletedChallenges()[index].creatorStatus){
                if (Resources.getCompletedChallenges()[index].creatorEmail == Resources.getCurrentUserEmail()) return Resources.getCompletedChallenges()[index].participantEmail + " won the challenge";
                else return "You won the challenge!"
            } else if (Resources.getCompletedChallenges()[index].participantStatus) {
                if (Resources.getCompletedChallenges()[index].participantEmail == Resources.getCurrentUserEmail()) return "You won the challenge!";
                else return Resources.getCompletedChallenges()[index].participantEmail + " won the challenge";
            } else if (!Resources.getCompletedChallenges()[index].participantStatus){
                if (Resources.getCompletedChallenges()[index].participantEmail == Resources.getCurrentUserEmail()) return Resources.getCompletedChallenges()[index].creatorEmail + " won the challenge";
                else return "You won the challenge!";
            }
        }

        function showMoreButton(val) {
            vm.showMoreButton = val.length > vm.completedChallengesLimit
        }

        function showMore() {
            vm.completedChallengesLimit += showMoreLimit;
            showMoreButton(Resources.getCompletedChallenges());
        }

        function showLess() {
            vm.completedChallengesLimit = showMoreLimit;
            showMoreButton(Resources.getCompletedChallenges());
            vm.showLessButton = false;
        }
    }
})();<commit_msg>Fixed bug when showing wrong winner of the challenges close #234<commit_after>(function () {
    CompletedChallengesController.$inject = ['Challenges', 'Resources', 'ProfileService', 'Utils'];

    angular
        .module('myApp.components.completedChallenges', [])
        .component('kudosChallengeCompleted', {
            templateUrl: 'app/components/kudos-challenge-completed/kudos-challenge-completed.html',
            controller: ('CompletedChallengesController',CompletedChallengesController),
            controllerAs: 'chCompleted'
        });

    function CompletedChallengesController(Challenges, Resources, ProfileService, Utils) {
        var vm = this,
            showMoreLimit = 5;

        vm.completedChallengesLimit = 5;
        vm.completedChallengesCollection = [];
        vm.showList = false;

        vm.acornPlural = Utils.acornPlural;
        vm.getWinner = getWinner;
        vm.showMore = showMore;
        vm.showLess = showLess;
        vm.showMoreButton = showMoreButton;

        vm.$onInit = onInit();

        function onInit() {
            Challenges.getCompletedChallenges().then(function (val) {
                Resources.setCompletedChallenges(val);
                vm.completedChallengesCollection = Resources.getCompletedChallenges();
                showMoreButton(val);
            });

            if(!Resources.getCurrentUserEmail()){
                ProfileService.userHome().then(function (val) {
                    Resources.setCurrentUserEmail(val.email);
                    vm.userEmail = Resources.getCurrentUserEmail();
                });
            } else {
                vm.userEmail = Resources.getCurrentUserEmail();
            }
        }

        function getWinner(index) {
            if (Resources.getCompletedChallenges()[index].creatorStatus) {
                if (Resources.getCompletedChallenges()[index].creatorEmail == Resources.getCurrentUserEmail()) return "You won the challenge!";
                else return Resources.getCompletedChallenges()[index].creatorEmail + " won the challenge";
            } else if (Resources.getCompletedChallenges()[index].creatorStatus == false){
                if (Resources.getCompletedChallenges()[index].creatorEmail == Resources.getCurrentUserEmail()) return Resources.getCompletedChallenges()[index].participantEmail + " won the challenge";
                else return "You won the challenge!"
            } else if (Resources.getCompletedChallenges()[index].participantStatus) {
                if (Resources.getCompletedChallenges()[index].participantEmail == Resources.getCurrentUserEmail()) return "You won the challenge!";
                else return Resources.getCompletedChallenges()[index].participantEmail + " won the challenge";
            } else if (Resources.getCompletedChallenges()[index].participantStatus == false){
                if (Resources.getCompletedChallenges()[index].participantEmail == Resources.getCurrentUserEmail()) return Resources.getCompletedChallenges()[index].creatorEmail + " won the challenge";
                else return "You won the challenge!";
            }
        }

        function showMoreButton(val) {
            vm.showMoreButton = val.length > vm.completedChallengesLimit
        }

        function showMore() {
            vm.completedChallengesLimit += showMoreLimit;
            showMoreButton(Resources.getCompletedChallenges());
        }

        function showLess() {
            vm.completedChallengesLimit = showMoreLimit;
            showMoreButton(Resources.getCompletedChallenges());
            vm.showLessButton = false;
        }
    }
})();<|endoftext|>


<commit_before>'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

const createLintingRule = () => ({
  test: /\.(js|vue)$/,
  loader: 'eslint-loader',
  enforce: 'pre',
  include: [resolve('src'), resolve('test')],
  options: {
    formatter: require('eslint-friendly-formatter'),
    emitWarning: !config.dev.showEslintErrorsInOverlay
  }
})

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
  module: {
    rules: [
      ...(config.dev.useEslint ? [createLintingRule()] : []),
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}
<commit_msg>update webpack alias<commit_after>'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

const createLintingRule = () => ({
  test: /\.(js|vue)$/,
  loader: 'eslint-loader',
  enforce: 'pre',
  include: [resolve('src'), resolve('test')],
  options: {
    formatter: require('eslint-friendly-formatter'),
    emitWarning: !config.dev.showEslintErrorsInOverlay
  }
})

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
      '_c': resolve('src/components'),
      '_conf': resolve('config')
    }
  },
  module: {
    rules: [
      ...(config.dev.useEslint ? [createLintingRule()] : []),
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const ngtools = require('@ngtools/webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

/**
 * Webpack Constants
 */
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const FABRIC8_WIT_API_URL = process.env.FABRIC8_WIT_API_URL || 'http://api.almighty.io/api/';
const FABRIC8_RECOMMENDER_API_URL = process.env.FABRIC8_RECOMMENDER_API_URL || 'http://api-bayesian.dev.rdu2c.fabric8.io/api/v1/';
const FABRIC8_FORGE_URL = process.env.FORGE_URL;
const PUBLIC_PATH = process.env.PUBLIC_PATH || '/';

const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: false,
  FABRIC8_WIT_API_URL: FABRIC8_WIT_API_URL,
  FABRIC8_RECOMMENDER_API_URL: FABRIC8_RECOMMENDER_API_URL,
  FABRIC8_FORGE_URL: FABRIC8_FORGE_URL,
  PUBLIC_PATH: PUBLIC_PATH

});

module.exports = function (env) {
  console.log('The env from the webpack.prod config: ' + JSON.stringify(env, null, 2));
  return webpackMerge(commonConfig({env: ENV}), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'cheap-module-source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),
      // path: path.join(process.cwd(), 'dist'),
      publicPath: METADATA.PUBLIC_PATH,

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].[chunkhash].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[name].[chunkhash].bundle.map',

      /**
       * The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].[chunkhash].chunk.js'

    },

    /**
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [

      /**
       * Plugin: @ngtools/webpack
       * Description: Set up AoT for webpack, including SASS precompile
       */
 /*     new ngtools.AotPlugin({
        tsConfigPath: 'tsconfig-aot.json',
        // mainPath: "src/main.browser.ts"
        // entryModule: 'src/app/app.module#AppModule',
        // genDir: 'aot'
      }),
*/
      /**
       * Plugin: WebpackMd5Hash
       * Description: Plugin to replace a standard webpack chunkhash with md5.
       *
       * See: https://www.npmjs.com/package/webpack-md5-hash
       */
      new WebpackMd5Hash(),

      /**
       * Webpack plugin and CLI utility that represents bundle content as convenient interactive zoomable treemap
       */
/*
      new BundleAnalyzerPlugin({
        generateStatsFile: true
      }),
*/

      /**
       * Plugin: DedupePlugin
       * Description: Prevents the inclusion of duplicate code into your bundle
       * and instead applies a copy of the function at runtime.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       * See: https://github.com/webpack/docs/wiki/optimization#deduplication
       */
      // new DedupePlugin(), // see: https://github.com/angular/angular-cli/issues/1587

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
          'FABRIC8_WIT_API_URL' : JSON.stringify(METADATA.FABRIC8_WIT_API_URL),
          'FABRIC8_RECOMMENDER_API_URL' : JSON.stringify(METADATA.FABRIC8_RECOMMENDER_API_URL),
          'FABRIC8_FORGE_URL': JSON.stringify(METADATA.FABRIC8_FORGE_URL),
          'PUBLIC_PATH' : JSON.stringify(METADATA.PUBLIC_PATH)
        }
      }),

      /**
       * Plugin: UglifyJsPlugin
       * Description: Minimize all JavaScript output of chunks.
       * Loaders are switched into minimizing mode.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
       */
      // NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
      new UglifyJsPlugin({
        // beautify: true, //debug
        // mangle: false, //debug
        // dead_code: false, //debug
        // unused: false, //debug
        // deadCode: false, //debug
        // compress: {
        //   screw_ie8: true,
        //   keep_fnames: true,
        //   drop_debugger: false,
        //   dead_code: false,
        //   unused: false
        // }, // debug
        // comments: true, //debug

        beautify: false, //prod
        mangle: {
          screw_ie8: true,
          keep_fnames: true
        }, //prod
        compress: {
          screw_ie8: true
        }, //prod
        comments: false //prod
      }),

      /**
       * Plugin: NormalModuleReplacementPlugin
       * Description: Replace resources that matches resourceRegExp with newResource
       *
       * See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
       */

      new NormalModuleReplacementPlugin(
        /angular2-hmr/,
        helpers.root('config/modules/angular2-hmr-prod.js')
      ),

      /**
       * Plugin: IgnorePlugin
       * Description: Don’t generate modules for requests matching the provided RegExp.
       *
       * See: http://webpack.github.io/docs/list-of-plugins.html#ignoreplugin
       */

      // new IgnorePlugin(/angular2-hmr/),

      /**
       * Plugin: CompressionPlugin
       * Description: Prepares compressed versions of assets to serve
       * them with Content-Encoding
       *
       * See: https://github.com/webpack/compression-webpack-plugin
       */
      //  install compression-webpack-plugin
      // new CompressionPlugin({
      //   regExp: /\.css$|\.html$|\.js$|\.map$/,
      //   threshold: 2 * 1024
      // })

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        debug: false,
        options: {

          /**
           * Static analysis linter for TypeScript advanced options configuration
           * Description: An extensible linter for the TypeScript language.
           *
           * See: https://github.com/wbuchwalter/tslint-loader
           */
          tslint: {
            emitErrors: true,
            failOnHint: true,
            resourcePath: 'src'
          },

          /**
           * Html loader advanced options
           *
           * See: https://github.com/webpack/html-loader#advanced-options
           */
          // TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
          htmlLoader: {
            minimize: true,
            removeAttributeQuotes: false,
            caseSensitive: true,
            customAttrSurround: [
              [/#/, /(?:)/],
              [/\*/, /(?:)/],
              [/\[?\(?/, /(?:)/]
            ],
            customAttrAssign: [/\)?\]?=/]
          }
        }
      })
    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: false,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
};
<commit_msg>Fix api url!<commit_after>/**
 * @author: @AngularClass
 */

const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev

/**
 * Webpack Plugins
 */
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const ngtools = require('@ngtools/webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

/**
 * Webpack Constants
 */
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const FABRIC8_WIT_API_URL = process.env.FABRIC8_WIT_API_URL || 'http://demo.api.almighty.io/api/';
const FABRIC8_RECOMMENDER_API_URL = process.env.FABRIC8_RECOMMENDER_API_URL || 'http://api-bayesian.dev.rdu2c.fabric8.io/api/v1/';
const FABRIC8_FORGE_URL = process.env.FORGE_URL;
const PUBLIC_PATH = process.env.PUBLIC_PATH || '/';

const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: false,
  FABRIC8_WIT_API_URL: FABRIC8_WIT_API_URL,
  FABRIC8_RECOMMENDER_API_URL: FABRIC8_RECOMMENDER_API_URL,
  FABRIC8_FORGE_URL: FABRIC8_FORGE_URL,
  PUBLIC_PATH: PUBLIC_PATH

});

module.exports = function (env) {
  console.log('The env from the webpack.prod config: ' + JSON.stringify(env, null, 2));
  return webpackMerge(commonConfig({env: ENV}), {

    /**
     * Developer tool to enhance debugging
     *
     * See: http://webpack.github.io/docs/configuration.html#devtool
     * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
     */
    devtool: 'cheap-module-source-map',

    /**
     * Options affecting the output of the compilation.
     *
     * See: http://webpack.github.io/docs/configuration.html#output
     */
    output: {

      /**
       * The output directory as absolute path (required).
       *
       * See: http://webpack.github.io/docs/configuration.html#output-path
       */
      path: helpers.root('dist'),
      // path: path.join(process.cwd(), 'dist'),
      publicPath: METADATA.PUBLIC_PATH,

      /**
       * Specifies the name of each output file on disk.
       * IMPORTANT: You must not specify an absolute path here!
       *
       * See: http://webpack.github.io/docs/configuration.html#output-filename
       */
      filename: '[name].[chunkhash].bundle.js',

      /**
       * The filename of the SourceMaps for the JavaScript files.
       * They are inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
       */
      sourceMapFilename: '[name].[chunkhash].bundle.map',

      /**
       * The filename of non-entry chunks as relative path
       * inside the output.path directory.
       *
       * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
       */
      chunkFilename: '[id].[chunkhash].chunk.js'

    },

    /**
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [

      /**
       * Plugin: @ngtools/webpack
       * Description: Set up AoT for webpack, including SASS precompile
       */
 /*     new ngtools.AotPlugin({
        tsConfigPath: 'tsconfig-aot.json',
        // mainPath: "src/main.browser.ts"
        // entryModule: 'src/app/app.module#AppModule',
        // genDir: 'aot'
      }),
*/
      /**
       * Plugin: WebpackMd5Hash
       * Description: Plugin to replace a standard webpack chunkhash with md5.
       *
       * See: https://www.npmjs.com/package/webpack-md5-hash
       */
      new WebpackMd5Hash(),

      /**
       * Webpack plugin and CLI utility that represents bundle content as convenient interactive zoomable treemap
       */
/*
      new BundleAnalyzerPlugin({
        generateStatsFile: true
      }),
*/

      /**
       * Plugin: DedupePlugin
       * Description: Prevents the inclusion of duplicate code into your bundle
       * and instead applies a copy of the function at runtime.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       * See: https://github.com/webpack/docs/wiki/optimization#deduplication
       */
      // new DedupePlugin(), // see: https://github.com/angular/angular-cli/issues/1587

      /**
       * Plugin: DefinePlugin
       * Description: Define free variables.
       * Useful for having development builds with debug logging or adding global constants.
       *
       * Environment helpers
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
       */
      // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
          'FABRIC8_WIT_API_URL' : JSON.stringify(METADATA.FABRIC8_WIT_API_URL),
          'FABRIC8_RECOMMENDER_API_URL' : JSON.stringify(METADATA.FABRIC8_RECOMMENDER_API_URL),
          'FABRIC8_FORGE_URL': JSON.stringify(METADATA.FABRIC8_FORGE_URL),
          'PUBLIC_PATH' : JSON.stringify(METADATA.PUBLIC_PATH)
        }
      }),

      /**
       * Plugin: UglifyJsPlugin
       * Description: Minimize all JavaScript output of chunks.
       * Loaders are switched into minimizing mode.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
       */
      // NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
      new UglifyJsPlugin({
        // beautify: true, //debug
        // mangle: false, //debug
        // dead_code: false, //debug
        // unused: false, //debug
        // deadCode: false, //debug
        // compress: {
        //   screw_ie8: true,
        //   keep_fnames: true,
        //   drop_debugger: false,
        //   dead_code: false,
        //   unused: false
        // }, // debug
        // comments: true, //debug

        beautify: false, //prod
        mangle: {
          screw_ie8: true,
          keep_fnames: true
        }, //prod
        compress: {
          screw_ie8: true
        }, //prod
        comments: false //prod
      }),

      /**
       * Plugin: NormalModuleReplacementPlugin
       * Description: Replace resources that matches resourceRegExp with newResource
       *
       * See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
       */

      new NormalModuleReplacementPlugin(
        /angular2-hmr/,
        helpers.root('config/modules/angular2-hmr-prod.js')
      ),

      /**
       * Plugin: IgnorePlugin
       * Description: Don’t generate modules for requests matching the provided RegExp.
       *
       * See: http://webpack.github.io/docs/list-of-plugins.html#ignoreplugin
       */

      // new IgnorePlugin(/angular2-hmr/),

      /**
       * Plugin: CompressionPlugin
       * Description: Prepares compressed versions of assets to serve
       * them with Content-Encoding
       *
       * See: https://github.com/webpack/compression-webpack-plugin
       */
      //  install compression-webpack-plugin
      // new CompressionPlugin({
      //   regExp: /\.css$|\.html$|\.js$|\.map$/,
      //   threshold: 2 * 1024
      // })

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({
        debug: false,
        options: {

          /**
           * Static analysis linter for TypeScript advanced options configuration
           * Description: An extensible linter for the TypeScript language.
           *
           * See: https://github.com/wbuchwalter/tslint-loader
           */
          tslint: {
            emitErrors: true,
            failOnHint: true,
            resourcePath: 'src'
          },

          /**
           * Html loader advanced options
           *
           * See: https://github.com/webpack/html-loader#advanced-options
           */
          // TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
          htmlLoader: {
            minimize: true,
            removeAttributeQuotes: false,
            caseSensitive: true,
            customAttrSurround: [
              [/#/, /(?:)/],
              [/\*/, /(?:)/],
              [/\[?\(?/, /(?:)/]
            ],
            customAttrAssign: [/\)?\]?=/]
          }
        }
      })
    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: false,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  });
};
<|endoftext|>


<commit_before>var Phase = require('html5/parser/phase').Phase;
var inBody = require('html5/parser/in_body_phase').Phase;
var HTML5 = require('html5')

var start_tag_handlers = {
	html: 'startTagHtml',
	caption: 'startTagCaption',
	colgroup: 'startTagColgroup',
	col: 'startTagCol',
	table: 'startTagTable',
	tbody: 'startTagRowGroup',
	tfoot: 'startTagRowGroup',
	thead: 'startTagRowGroup',
	td: 'startTagImplyTbody',
	th: 'startTagImplyTbody',
	tr: 'startTagImplyTbody',
	'-default': 'startTagOther',
}

var end_tag_handlers = {
	table: 'endTagTable',
	body: 'endTagIgnore',
	caption: 'endTagIgnore',
	col: 'endTagIgnore',
	colgroup: 'endTagIgnore',
	html: 'endTagIgnore',
	tbody: 'endTagIgnore',
	td: 'endTagIgnore',
	tfoot: 'endTagIgnore',
	th: 'endTagIgnore',
	thead: 'endTagIgnore',
	tr: 'endTagIgnore',
	'-default': 'endTagOther',
}

exports.Phase = p = function InTablePhase(parser, tree) {
	Phase.call(this, parser, tree);
	this.start_tag_handlers = start_tag_handlers;
	this.end_tag_handlers = end_tag_handlers;
};

p.prototype = new Phase;

p.prototype.processCharacters =  function(data) {
	this.parse_error("unexpected-char-implies-table-voodoo");
	this.tree.insert_from_table = true;
	new inBody(this.parser, this.tree).processCharacters(data);
	this.tree.insert_from_table = false;
}

p.prototype.startTagCaption = function(name, attributes) {
	this.clearStackToTableContext();
	this.tree.activeFormattingElements.push(HTML5.Marker);
	this.tree.insert_element(name, attributes);
	this.parser.newPhase('inCaption');
}

p.prototype.startTagColgroup = function(name, attributes) {
	this.clearStackToTableContext();
	this.tree.insert_element(name, attributes);
	this.parser.newPhase('inColumnGroup');
}

p.prototype.startTagCol = function(name, attributes) {
	this.startTagColgroup('colgroup', {});
	this.parser.phase.processStartTag(name, attributes);
}

p.prototype.startTagRowGroup = function(name, attributes) {
	this.clearStackToTableContext();
	this.tree.insert_element(name, attributes);
	this.parser.newPhase('inTableBody');
}

p.prototype.startTagImplyTbody = function(name, attributes) {
	this.startTagRowGroup('tbody', {});
	this.parser.phase.processStartTag(name, attributes);
}

p.prototype.startTagTable = function(name, attributes) {
	this.parse_error("unexpected-start-tag-implies-end-tag",
            {startName: "table", endName: "table"});
	this.parser.phase.processEndTag('table');
	if(!this.parser.inner_html) this.parser.phase.processStartTag(name, attributes);
}

p.prototype.startTagOther = function(name, attributes) {
	this.parse_error("unexpected-start-tag-implies-table-voodoo", {name: name});
	this.tree.insert_from_table = true;
	new inBody(this.parser, this.tree).processStartTag(name, attributes);
	this.tree.insert_from_table = false;
}

p.prototype.endTagTable = function(name) {
	if(this.inScope(name, true)) {
		this.tree.generateImpliedEndTags();
		if(this.tree.open_elements.last().tagName.toLowerCase() != name) {
			this.parse_error("end-tag-too-early-named", {gotName: 'table', expectedName: this.tree.open_elements.last().tagName.toLowerCase()});
		}

		this.tree.remove_open_elements_until('table');
		this.parser.reset_insertion_mode();
	} else {
		assert.ok(this.parser.inner_html);
		this.parse_error();
	}
}

p.prototype.endTagIgnore = function(name) {
	this.parse_error("unexpected-end-tag", {name: name});
}

p.prototype.endTagOther = function(name) {
	this.parse_error("unexpected-end-tag-implies-table-voodoo", {name: name})
	// Make all the special element rearranging voodoo kick in
	this.tree.insert_from_table = true
	// Process the end tag in the "in body" mode
	new inBody(this.parser, this.tree).processEndTag(name)
	this.tree.insert_from_table = false
}

p.prototype.clearStackToTableContext = function() {
	var name;
	while(name = this.tree.open_elements.last().tagName.toLowerCase(), (name != 'table' && name != 'html')) {
		this.parse_error("unexpected-implied-end-tag-in-table", {name: name})
		this.tree.pop_element()
	}
	// When the current node is <html> it's an inner_html case
}
<commit_msg>- define assert in in_table_phase for a check of inner_html mode<commit_after>var Phase = require('html5/parser/phase').Phase;
var inBody = require('html5/parser/in_body_phase').Phase;
var HTML5 = require('html5')
var assert = require('assert')

var start_tag_handlers = {
	html: 'startTagHtml',
	caption: 'startTagCaption',
	colgroup: 'startTagColgroup',
	col: 'startTagCol',
	table: 'startTagTable',
	tbody: 'startTagRowGroup',
	tfoot: 'startTagRowGroup',
	thead: 'startTagRowGroup',
	td: 'startTagImplyTbody',
	th: 'startTagImplyTbody',
	tr: 'startTagImplyTbody',
	'-default': 'startTagOther',
}

var end_tag_handlers = {
	table: 'endTagTable',
	body: 'endTagIgnore',
	caption: 'endTagIgnore',
	col: 'endTagIgnore',
	colgroup: 'endTagIgnore',
	html: 'endTagIgnore',
	tbody: 'endTagIgnore',
	td: 'endTagIgnore',
	tfoot: 'endTagIgnore',
	th: 'endTagIgnore',
	thead: 'endTagIgnore',
	tr: 'endTagIgnore',
	'-default': 'endTagOther',
}

exports.Phase = p = function InTablePhase(parser, tree) {
	Phase.call(this, parser, tree);
	this.start_tag_handlers = start_tag_handlers;
	this.end_tag_handlers = end_tag_handlers;
};

p.prototype = new Phase;

p.prototype.processCharacters =  function(data) {
	this.parse_error("unexpected-char-implies-table-voodoo");
	this.tree.insert_from_table = true;
	new inBody(this.parser, this.tree).processCharacters(data);
	this.tree.insert_from_table = false;
}

p.prototype.startTagCaption = function(name, attributes) {
	this.clearStackToTableContext();
	this.tree.activeFormattingElements.push(HTML5.Marker);
	this.tree.insert_element(name, attributes);
	this.parser.newPhase('inCaption');
}

p.prototype.startTagColgroup = function(name, attributes) {
	this.clearStackToTableContext();
	this.tree.insert_element(name, attributes);
	this.parser.newPhase('inColumnGroup');
}

p.prototype.startTagCol = function(name, attributes) {
	this.startTagColgroup('colgroup', {});
	this.parser.phase.processStartTag(name, attributes);
}

p.prototype.startTagRowGroup = function(name, attributes) {
	this.clearStackToTableContext();
	this.tree.insert_element(name, attributes);
	this.parser.newPhase('inTableBody');
}

p.prototype.startTagImplyTbody = function(name, attributes) {
	this.startTagRowGroup('tbody', {});
	this.parser.phase.processStartTag(name, attributes);
}

p.prototype.startTagTable = function(name, attributes) {
	this.parse_error("unexpected-start-tag-implies-end-tag",
            {startName: "table", endName: "table"});
	this.parser.phase.processEndTag('table');
	if(!this.parser.inner_html) this.parser.phase.processStartTag(name, attributes);
}

p.prototype.startTagOther = function(name, attributes) {
	this.parse_error("unexpected-start-tag-implies-table-voodoo", {name: name});
	this.tree.insert_from_table = true;
	new inBody(this.parser, this.tree).processStartTag(name, attributes);
	this.tree.insert_from_table = false;
}

p.prototype.endTagTable = function(name) {
	if(this.inScope(name, true)) {
		this.tree.generateImpliedEndTags();
		if(this.tree.open_elements.last().tagName.toLowerCase() != name) {
			this.parse_error("end-tag-too-early-named", {gotName: 'table', expectedName: this.tree.open_elements.last().tagName.toLowerCase()});
		}

		this.tree.remove_open_elements_until('table');
		this.parser.reset_insertion_mode();
	} else {
		assert.ok(this.parser.inner_html);
		this.parse_error();
	}
}

p.prototype.endTagIgnore = function(name) {
	this.parse_error("unexpected-end-tag", {name: name});
}

p.prototype.endTagOther = function(name) {
	this.parse_error("unexpected-end-tag-implies-table-voodoo", {name: name})
	// Make all the special element rearranging voodoo kick in
	this.tree.insert_from_table = true
	// Process the end tag in the "in body" mode
	new inBody(this.parser, this.tree).processEndTag(name)
	this.tree.insert_from_table = false
}

p.prototype.clearStackToTableContext = function() {
	var name;
	while(name = this.tree.open_elements.last().tagName.toLowerCase(), (name != 'table' && name != 'html')) {
		this.parse_error("unexpected-implied-end-tag-in-table", {name: name})
		this.tree.pop_element()
	}
	// When the current node is <html> it's an inner_html case
}
<|endoftext|>