Namy
Gets the name of the exported function.

@name Namy
@function
@param {String} input The path to the package.json, directory or the file.
@param {Function} callback The callback function.
965606
function Namy(input, callback) {
    if (/package.json$/.test(input)) {
        return ReadJson(input, function (err, data) {
            if (err) { return callback(err); }
            if (!data.main) {
                return callback(new Error("Cannot find the main field in package.json"));
            }
            Namy(data.main, callback);
        });
    }

    var path = null
      , isInCache = null
      , res = null
      , name = null
      ;

    try {
        path = require.resolve(input)
        isInCache = !!require.cache[path]
        // TODO Make this async
        res = require(input)
    } catch (err) {
        return callback(err);
    }

    if (typeof res === "function") {
        name = res.name || null;
    } else {
        return callback(new Error("The module does not export a function."));
    }

    if (!isInCache) {
        delete require.cache[path];
    }

    if (!name) {
        return callback(new Error("The function does not have a name."));
    }

    callback(null, name);
}
437237
function (data) {

            if (!isLog()) {
                return undefined;
            }

            try {
                _fs.appendFileSync("pkgscript.log", (_utils.now() + "  " + data + "\n"), "utf8");

            } catch (e) {
                console.error(_utils.now + " [package-script] Package Script, ERROR:", e);
            }
        }
897887
function(callback){
    var argFiles,
        filePath,
        i;

    if(!program.files || program.files.length === 0){
        return callback(null, true);
    }

    argFiles = program.files.split(',');

    output("Loading files...");

    for(i=0; i<argFiles.length; i++){
        filePath = path.resolve(__dirname, argFiles[i].toString());
        output("Reading file..." + filePath);
        if(fs.existsSync(filePath)){
            files.push(fs.readFileSync(filePath));
        }else{
            return callback("File does not exist, " + filePath, false);
        }
    }

    callback(null, true);
}
261890
function main() {
    var program = require('commander')
    program.usage('FILE.d.ts... [options]')
    program.commandHelp = function() { return "  Convert *.d.ts files to TypeScript Declaration Core\n" }
    program.option('--pretty', 'Print pretty JSON, for human inspection')
        .option('--silent', 'Print nothing')
        .option('--lib', "Include TypeScript\'s lib.d.ts file")
    program.parse(process.argv)

    if (program.args.length < 1) {
        program.help()
    }

    var inputs = program.args.map(function(file) {
        return {
            file: file,
            text: fs.readFileSync(file, 'utf8')
        }
    })
    if (program.lib) {
        inputs.unshift({
            file: ">lib.d.ts",
            text: fs.readFileSync(__dirname + '/lib/lib.d.ts', 'utf8')
        })
    }
    var json = convert(inputs)
    if (program.silent)
        {}
    else if (program.pretty)
        console.log(util.inspect(json, {depth:null}))
    else
        console.log(JSON.stringify(json))
}
313243
function Pa () {

  var paFile = path.resolve('package.json');

  var writePackageJson = function (json) {
    fs.writeFileSync(paFile, JSON.stringify(json, null, 2));
  };

  this.init = function () {
    this.pkg = require(paFile);
    return this;
  };

  this.get = function (key) {
    var val = this.pkg[key] || this.pkg[require('./alias').init().aliases[key]];
    if (typeof val === 'undefined') {
      return ('can not read property ' + key + ' from package.json').red;
    }
    return (typeof val === 'object' ? JSON.stringify(val, null, 2) : val).green;
  };

  this.set = function (key, value) {
    key = this.pkg[key] ? key : require('./alias').init().aliases[key];
    this.pkg[key] = value;
    writePackageJson(this.pkg);
    return ("set key '" + key + "' to value '" + value + "'").green;
  };

  this.trigger = function (argv) {
    switch (argv._.length) {
      case 0:
        return JSON.stringify(this.pkg, null, 2).green;
      case 1:
        return this.get(argv._[0]);
      case 2:
        return this.set(argv._[0], argv._[1]);
      default:
        return "something bad happened, just run 'pa [key] [value]' to set the new value in your package.json";
    }

  };

}
96616
function resolveInputFile(args) {
    const { file } = args;
    return file ? resolve(path.resolve(file)) : build(args);
}
1277846
function validateSourcePath(sourcePath) {
    const materialPackageJSONPath = pathUtils.resolve(sourcePath, 'package.json');

    return fs.readFileAsync(materialPackageJSONPath, { encoding: 'UTF8' })
        .then(materialPackageJSONString => {
            const package = JSON.parse(materialPackageJSONString);
            if (package.name !== sourcePackageName) {
                throw new Error(`Source path ${sourcePath} does not appear to be a clone of https://github.com/callemall/material-ui`);
            }
            return sourcePath;
        });
}
380368
function executeCommand(parameters) {
    const configFilePath = path.join(process.cwd(), plugin.config.modulesPath, parameters.name);
    return mkdirpAsync(configFilePath)
    .then(() => {
      // We create the package.json file
      const packageJson = {
        'name': parameters.name,
        'version': '0.0.0',
        dependencies: {}
      };
      _.forEach(parameters.dependencies, moduleName => {
        packageJson.dependencies[moduleName] = '../' + moduleName;
      });
      // We save the specification in a json file
      return fs.writeFileAsync(configFilePath + path.sep + 'package.json', JSON.stringify(packageJson, null, 2));
    })
    .then(() => {
      const msg = '\n  The node module ' + icli.format.info(parameters.name) + ' has been created\n'
                + '  It is located in ' + icli.format.info(configFilePath) + ' you can start to implement it there.\n'
                + '  To import it in an existing Lambda, edit the file '
                + icli.format.info(path.join(process.cwd(), plugin.config.lambdasPath, '<lambda-identifier>', 'package.json'))
                + ' and add ' + icli.format.info('"' + parameters.name + '": "../modules/' + parameters.name + '"')
                + ' in the section ' + icli.format.info('dependencies') + '\n';
      icli.print(msg);
    });
  }
1282114
function packResult(args, proto, ObjName) {
    debug && logger.trace("Package Data To Client [ %s ]", JSON.stringify(args));
    if (null == proto) {
        logger.error('No proto File Configured！');
        return "";
    } else if (typeof proto == "string") {
        if (fs.existsSync(proto)) {
            proto = ProtoBuf.loadProtoFile(proto);
        } else if (fs.existsSync(proto + ".proto")) {
            proto = ProtoBuf.loadProtoFile(proto + ".proto");
        } else {
            return "";
        }
    }

    var RetMessage = proto.build("Ret" + ObjName);
    try {
        var ret_msg = new RetMessage();
    } catch (e) {
        console.log(RetMessage, e);
    }

    for (var index in args) {
        if (args.hasOwnProperty(index)) {
            ret_msg[index] = args[index];
        }
    }

    return ret_msg.toBase64();
}
219590
function parentName (options) {
  function instantiate (input) {
    if (/^[A-Z]{3}/.test(input)) {
      return input.replace(/^([A-Z]+)([A-Z])/, function (str, p1, p2) {
        return p1.toLowerCase() + p2
      })
    } else {
      return input.charAt(0).toLowerCase() + input.slice(1)
    }
  }

  /* don't bother with a parentName for exported identifiers */
  if (this.isExported) return ''

  if (this.memberof && this.kind !== 'constructor') {
    var parent = arrayify(options.data.root).find(where({ id: this.memberof }))
    if (parent) {
      if (this.scope === 'instance') {
        var name = parent.typicalname || parent.name
        return instantiate(name)
      } else if (this.scope === 'static' && !(parent.kind === 'class' || parent.kind === 'constructor')) {
        return parent.typicalname || parent.name
      } else {
        return parent.name
      }
    } else {
      return this.memberof
    }
  }
}
1050636
function find(input, options, callback) {
  expand(input, options, done)

  function done(error, result) {
    /* istanbul ignore if - glob errors are unusual.
     * other errors are on the vfile results. */
    if (error) {
      callback(error)
    } else {
      callback(null, {oneFileMode: oneFileMode(result), files: result.output})
    }
  }
}
1287566
function lodashFunctionToString(functionName) {
	var moduleText = readFileSync(localRequire.resolve(getLodashId(functionName)), 'utf-8');

	return function () {
		return 'function '+functionName+'() {var module = {exports:{}};'+moduleText+'\nreturn module.exports.apply({}, arguments);};';
	}
}
782963
private static String formatOutput(String js, boolean export) {
    StringBuilder output = new StringBuilder();

    // Shadow window so that non-browser environments can pass their own global object here.
    output.append("(function(window){");

    // If $wnd is set to this, then JSInterop's normal export will run, and pollute the global
    // namespace. If export is false, fake out $wnd with an empty object.
    // (We also add Error to work around StackTraceCreator using it in a static block).
    output.append("var $wnd=").append(export ? "this" : "{'Error':{}}").append(";");

    // Shadow $doc, $moduleName and $moduleBase.
    output.append("var $doc={},$moduleName,$moduleBase;");

    // Append output JS.
    output.append(js);

    // 1. Export $gwtExport, needed for transpile.js
    // 2. Reset $wnd (nb. this occurs after jscompiler's JS has run)
    // 3. Call gwtOnLoad, if defined: this invokes onModuleLoad for all loaded modules.
    output.append("this['$gwtExport']=$wnd;$wnd=this;typeof gwtOnLoad==='function'&&gwtOnLoad()");

    // Overspecify the global object, to capture Node and browser environments.
    String globalObject = "this&&this.self||"
        + "(typeof window!=='undefined'?window:(typeof global!=='undefined'?global:this))";

    // Call the outer function with the global object as this and its first argument, so that we
    // fake window in Node environments, allowing our code to do things like "window.console(...)".
    output.append("}).call(").append(globalObject).append(",").append(globalObject).append(");");

    return output.toString();
  }
458497
function updateComponentsJS(newFileName) {

  console.log(" 🔰  updating: ".cyan + "components.js".white);

  if (process.cwd().includes('client/app/components') === false) {
    process.chdir(`./client/app/components`);
  }

  componentsArray = [];
  genArr = [];


  // sync app.component with updates
  fs.readdir(process.cwd(), function (err, items) {
    genArr = items;
    generateDirectArray(genArr);
  });


  function generateDirectArray(items) {
    for (var i = 0; i < items.length; i++) {
      if (isDirectory(items[i])) {
      } else {
        componentsArray.push(items[i]);
      }
    }
    importStringGenerator();
  }

  function isDirectory(inputString) {
    var str = inputString;
    var patt = new RegExp("[.]");
    var res = patt.test(str);
    return res;
  }

  String.prototype.capitalizeFirstLetter = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
  }

  function importStringGenerator() {
    if (typeof newFileName != 'undefined') {
      componentsArray.push(`${newFileName}`);
    }

    genString = "";
    for (var i = 0; i < componentsArray.length; i++) {
      genString = genString + `    import ${componentsArray[i].capitalizeFirstLetter()}Module from './${componentsArray[i]}/${componentsArray[i]}.module';\r`
    }
    listString = "";
    for (var i = 0; i < componentsArray.length; i++) {

      // check if last in list in order to not include comma
      if (i === (componentsArray.length - 1)) {
        listString = listString + `     ${componentsArray[i].capitalizeFirstLetter()}Module` + `.name \r`
      } else {
        listString = listString + `     ${componentsArray[i].capitalizeFirstLetter()}Module` + '.name, \r'
      }

    }


    fs.writeFile("components.js", `import angular from 'angular';
${genString}

const ComponentsModule = angular.module('app.components',[
  ${listString}
]);

export default ComponentsModule;

  `, function (err) {
      if (err) {
        return console.log(` ❌  failed to update due to error:  ${err}`);
      }
      console.log(" 🔰  updated: ".cyan + "components.js".white);
    });
  }
}
1349004
function buildPackage(callback) {

    var dirMap = self.build.dirMap,
        i = dirMap.length,
        filepath,
        pkgName = '/package.json',
        pkgLength = pkgName.length,
        list = [];

    // search dirmap for package.json
    while(i--) {
      filepath = dirMap[i];
      if (filepath.slice(filepath.length - pkgLength, filepath.length) === pkgName) {
        list.push(filepath);
      }
    }

    function resolvePackage(filepath, callback) {
      var dirname = filepath.slice(0, filepath.length - pkgLength);
      var fullpath = path.resolve(self.piccolo.get('modules'), './' + filepath);

      var response = { key: dirname };

      fs.readFile(fullpath, 'utf8', function (error, content) {
        if (error) return callback(error, null);

        // remove BOM
        content = removeBOM(content);

        // use index if filepath is empty
        var filepath;
        if (content === '') {
          filepath = path.resolve(dirname, 'index.js');
        }

        // read JSON file
        var result;
        try {
          result = JSON.parse(content);
        } catch (e) {
          return callback(e, null);
        }

        if (result.main) {
          filepath = path.resolve(dirname, result.main);
        } else {
          filepath = path.resolve(dirname, './index.js');
        }

        // check that file exist
        var fullpath = path.resolve(self.piccolo.get('modules'), './' + filepath);
        fs.exists(fullpath, function (exist) {
          response.value = exist ? filepath : false;
          callback(null, response);
        });
      });
    }

    // read all package.json files and resolve the filepath
    async.map(list, resolvePackage, function (error, list) {
      if (error) return callback(error, null);

      var final = {};
      list.forEach(function (obj) {
        final[obj.key] = obj.value;
      });

      // save resolved packageMap
      self.build.packageMap = final;
      callback(null, null);
    });
  }
7542
function bundle(input, nc, options, complete) {
  const bundlePath = path.join(nc, 'lib', 'nexe.js');
  const mapfile = options.output + '.map';
  let ws = fs.createWriteStream(bundlePath);

  const igv = '__filename,__dirname,_process';
  let insertGlobalVars = { isNexe: true },
    wantedGlobalVars = igv.split(',');

  // parse insertGlobalVars.
  Object.keys(insertGlobals.vars).forEach(function(x) {
    if (wantedGlobalVars.indexOf(x) === -1) {
      insertGlobalVars[x] = undefined;
    }
  });

  let paths = [path.join(nc, 'lib')];

  if (options.browserifyPaths) {
    paths = paths.concat(options.browserifyPaths);
  }

  _log('executing browserify via API');
  let bproc = browserify([input], {
    debug: options.debug,
    commondir: false,
    paths: paths,
    builtins: false,
    insertGlobalVars: insertGlobalVars,
    detectGlobals: true,
    browserField: false,
  });

  if (options.browserifyExcludes && Array.isArray(options.browserifyExcludes)) {
    for (let i = 0; i < options.browserifyExcludes.length; i++) {
      let lib = options.browserifyExcludes[i];
      _log("Excluding '%s' from browserify bundle", lib);
      bproc.exclude(lib);
    }
  }

  // copy the excludes code for requires for now.
  if (options.browserifyRequires && Array.isArray(options.browserifyRequires)) {
    for (let i = 0; i < options.browserifyRequires.length; i++) {
      let lib = options.browserifyRequires[i];
      let name = lib.file || lib; // for  object format.
      // if `lib` is object then fetch all params without `file`
      // otherwise returns empty object
      let opts =
        (lib instanceof Object &&
          Object.keys(lib)
            .filter(key => key !== 'file')
            .reduce((acc, key) => {
              return (acc[key] = lib[key]), acc;
            }, {})) ||
        {};

      _log("Force including '%s' in browserify bundle", name);
      bproc.require(lib, opts);
    }
  }

  if (options.debug) {
    bproc.require(require.resolve('source-map-support'));
  }

  let bprocbun = bproc
    .bundle() // bundle
    .pipe(ws); // pipe to file

  // error on require errors, still can't contionue. ffs browserify
  bprocbun.on('error', function(err) {
    _log('error', '[browserify] ' + err);
  });

  ws.on('error', function(err) {
    console.log(err);
    _log('error', 'Failed to save stdout to disk');
    process.exit(1);
  });

  ws.on('close', function() {
    var source = fs.readFileSync(bundlePath, 'utf8');
    source = source.replace(/[^\x00-\x7F]/g, '');

    // write the source modified to nexe.js
    fs.writeFile(bundlePath, source, 'utf8', function(err) {
      if (err) {
        _log('error', 'failed to save source');
        process.exit(1);
      }

      complete();
    });
  });
}
659263
function validateFunction(path, driver, functionName) {
  if (typeof driver[functionName] !== 'function') {
    console.error(`${path} missing .${functionName}() implementation`);
    process.exit(1);
  }
}