A Node module (not a Grunt task itself) to help in loading NPM-based tasks without requiring a "package.json"
file next to every Gruntfile. To be used as an alternative to `grunt.loadNpmTasks`/`grunt.task.loadNpmTasks`.
510084
function GruntTaskLoader(grunt) {
  // Don't require the `new` keyword
  if (!(this instanceof GruntTaskLoader)) {
    return new GruntTaskLoader(grunt);
  }

  // Validate the input
  if (!
      (
        grunt &&
        typeof grunt.loadNpmTasks === 'function' &&
        grunt.task && typeof grunt.task.loadNpmTasks === 'function' &&
        grunt.file && typeof grunt.file.findup === 'function'
      )
  ) {
    throw new TypeError('The `grunt` argument did not match expectations');
  }

  // Save references to the Grunt instance's original `loadNpmTasks` method definition
  var _grunt_loadNpmTasks = grunt.loadNpmTasks;

  this.loadNpmTasks = function(name) {
    var requiredFile, folderIndex, filepath,
        modulePartialPath = 'node_modules/' + name;
    try {
      requiredFile = require.resolve(name);
    }
    catch (e) {
      requiredFile = null;
    }

    if (requiredFile &&
        requiredFile.length > modulePartialPath.length &&
        (
          (folderIndex = requiredFile.indexOf(modulePartialPath)) &&
          folderIndex !== -1 &&
          (
            folderIndex === (requiredFile.length - modulePartialPath.length) ||
            requiredFile.charAt(folderIndex + modulePartialPath.length) === '/'
          )
        )
    ) {
      filepath = requiredFile.slice(0, folderIndex + modulePartialPath.length);
    }
    else {
      // TODO: Verify the initial `require.resolve` approach should already cover this whole scenario. If so, remove the `findup` dependency.
      filepath = grunt.file.findup(modulePartialPath, {
        cwd: path.resolve('node_modules', name),
        nocase: true
      });
    }

    // If we found a magically hidden version of this Node module while ignoring "package.json" files
    if (filepath) {
      _grunt_loadNpmTasks.call(grunt, path.relative(path.resolve('node_modules'), filepath));
    }
    else {
      // Let Grunt do its thing and hope for the best (e.g. that there is a "gruntcollection" at play)
      _grunt_loadNpmTasks.call(grunt, name);
    }
  };
  this.loadNpmTasks.bind(this);
}
164779
function prepareGrunt(grunt) {
    var allFiles = [
        'package.json',
        'Gruntfile.js',
        'lib/**/*.js',
        'spec/**/*',
        '.jshintrc',
        'spec/**/.jshintrc',
        'lib/**/.jshintrc'
    ];

    var allConfigFiles = [
        'Gruntfile.js'
    ];

    var allLibFiles = [
        'Gruntfile.js',
        'lib/**/*.js',
        'index.js'
    ];

    var allSpecFiles = [
        'spec/**/*-spec.js'
    ];

    var allIgnoreFiles = [
        'node_modules/**/*',
        'spec/**/*-disabled.js'
    ];

    // grunt configuration.
    grunt.initConfig({

        // grunt-contrib-jshint
            jshint: {
                // grunt jshint:source
                // will check the source files only
                source: {
                    src: allLibFiles
                },
                // grunt jshint:spec
                // will check the spec files only
                spec: {
                    src: allSpecFiles,
                    // use test specific .jshintrc for spec folder
                    options: {
                        jshintrc: 'spec/.jshintrc'
                    }
                },
                options: {
                    // default to the root .jshintrc
                    jshintrc: '.jshintrc',

                    // ensure we don't waste our time on files we have
                    // explicitly disabled or that we have brought in from
                    // other libraries.
                    ignores: allIgnoreFiles
                }
            },

        // grunt-contrib-watch
            watch: {
                // use with 'grunt watch' from command line ensure we reload
                // our watches when ANY of these files change.
                files: allConfigFiles,
                options: {
                    reload: true
                },
                jshint: {
                    files: allFiles,
                    tasks: ['jshint'],
                    options:{
                        interrupt: true,
                        atBegin: true
                    }
                },
                // grunt watch:mochaTest
                mochaTest: {
                    files: allFiles,
                    tasks: ['coverage'],
                    options:{
                        interrupt: true,
                        atBegin: true
                    }
                }
            },

        // grunt-mocha-test
            mochaTest: {
                // run all tests
                test: {
                    options: {
                        reporter: 'spec',
                        require: 'spec/helper'
                    },
                    src: allSpecFiles
                },
                min: {
                    options: {
                        reporter: 'spec',
                        require: 'spec/helper'
                    },
                    src: allSpecFiles
                }
            },

            'mocha_istanbul': {
                coverage: {
                    src: 'spec',
                    options: {
                        excludes: [
                            'spec/**/*.js'
                        ],
                        mask: '**/*-spec.js',
                        reportFormats: ['html'],
                        mochaOptions: [
                            '--require',
                            'spec/helper'
                        ]
                    }
                }
            }
        });

    // These plugins provide necessary tasks.
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-mocha-test');
    grunt.loadNpmTasks('grunt-mocha-istanbul');
    grunt.loadNpmTasks('grunt-notify');

    // Whenever the "coverage" task is run, run these tasks
    grunt.registerTask('coverage', ['mocha_istanbul:coverage']);

    // Whenever the "test" task is run, run these tasks
    grunt.registerTask('test', ['jshint', 'mochaTest:test']);

    // By default, lint and run all tests.
    grunt.registerTask('default', ['jshint', 'coverage']);
}
1295693
function loadPackageJSONConfigFile(filePath) {
    debug(`Loading package.json config file: ${filePath}`);
    try {
        return loadJSONConfigFile(filePath).eslintConfig || null;
    } catch (e) {
        debug(`Error reading package.json file: ${filePath}`);
        e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
        throw e;
    }
}
170963
async function create(name, options, api, env) {
  // Grab the cwd and npmClient off of the environment. We can use these to
  // create the folder for the project and for determining what client to use
  // for npm-related commands
  const { CLI_ENV, cwd, npmClient } = env;
  // We support a couple of options for our `create` command, some only exist
  // during development (like link and linkCli).
  const { link, linkCli, plugins = [], presets = [], skip } = options;
  const root = path.join(cwd, name);

  logger.trace('Creating project:', name, 'at:', root);

  if (await fs.exists(root)) {
    throw new Error(`A folder already exists at \`${root}\``);
  }

  // Create the root directory for the new project
  await fs.ensureDir(root);

  const {
    writePackageJson,
    installDependencies,
    linkDependencies,
  } = await createClient(npmClient, root);
  const packageJson = {
    name,
    private: true,
    license: 'MIT',
    scripts: {},
    dependencies: {},
    devDependencies: {},
    toolkit: {},
  };

  // Write the packageJson to the newly created `root` folder
  await writePackageJson(packageJson);

  const installer = linkCli ? linkDependencies : installDependencies;
  await installer(['@carbon/toolkit']);

  if (CLI_ENV === 'production') {
    clearConsole();
  }

  if (skip) {
    displaySuccess(root, name, npmClient);
    return;
  }

  const toolkit = await which('toolkit', { cwd: root });

  if (presets.length > 0) {
    const args = ['add', ...presets, link && '--link'].filter(Boolean);
    await spawn(toolkit, args, {
      cwd: root,
      stdio: 'inherit',
    });
  }

  if (plugins.length > 0) {
    const args = ['add', ...plugins, link && '--link'].filter(Boolean);
    await spawn(toolkit, args, {
      cwd: root,
      stdio: 'inherit',
    });
  }

  displaySuccess(root, name, npmClient);
}
1028868
function requireWrapper(baseModule, moduleId)
{
  var componentPath
      // translate module to path alias
    , modulePath = this.checkPath(moduleId)
      // get first part of the module path
    , component = (modulePath || '').split('/')[0]
    ;

  // shortcut for `empty:` path
  if (modulePath == 'empty:')
  {
    return {};
  }

  // check if name and path belong to the app or to node_modules
  if (component && component[0] != '.')
  {
    // - existing file vs. node_modules case
    if (component == modulePath)
    {
      componentPath = path.resolve(this.basePath, modulePath + '.js');
    }
    // - existing folder vs. node_modules member case
    else
    {
      componentPath = path.resolve(this.basePath, component);
    }

    if (fs.existsSync(componentPath))
    {
      // everything fits nicely, get the full thing
      // file might not exist at this point
      // but its legit developer's error
      modulePath = path.resolve(this.basePath, modulePath);
    }
  }

  if (this.disableCache)
  {
    delete require.cache[require.resolve(modulePath)];
  }

  return baseModule.require(modulePath);
}
899916
function npmInstall(requires, done) {
    var npmBin = path.join(path.dirname(process.argv[0]), 'npm');
    if (process.platform === 'win32') { npmBin += '.cmd'; }
    async.forEachSeries(requires, function(module, next) {
      // skip existing modules
      if (grunt.file.exists(path.join('./node_modules/' + module))) {
        grunt.log.writeln(String('Module "' + module + '" already installed, skipping.').cyan);
        return next();
      }
      grunt.log.writeln('npm install ' + module + ' --save');
      // spawn npm install
      var s = grunt.util.spawn({
        cmd: npmBin,
        args: ['install', module, '--save']
      }, next);
      // write output
      s.stdout.on('data', function(buf) { grunt.log.write(String(buf)); });
      s.stderr.on('data', function(buf) { grunt.log.write(String(buf)); });
    }, done);
  }
1149281
function packRequirements() {
  if (this.options.zip) {
    if (this.serverless.service.package.individually) {
      return BbPromise.resolve(this.targetFuncs)
        .map(f => {
          if (!get(f, 'module')) {
            set(f, ['module'], '.');
          }
          return f;
        })
        .then(funcs => uniqBy(funcs, f => f.module))
        .map(f => {
          this.serverless.cli.log(
            `Zipping required Python packages for ${f.module}...`
          );
          f.package.include.push(`${f.module}/.requirements.zip`);
          return addTree(
            new JSZip(),
            `.serverless/${f.module}/requirements`
          ).then(zip => writeZip(zip, `${f.module}/.requirements.zip`));
        });
    } else {
      this.serverless.cli.log('Zipping required Python packages...');
      this.serverless.service.package.include.push('.requirements.zip');
      return addTree(new JSZip(), '.serverless/requirements').then(zip =>
        writeZip(zip, path.join(this.servicePath, '.requirements.zip'))
      );
    }
  }
}
181956
static function packageJson($project_directory, $app_engine_project, $app_engine_service, $package_json_defaults = []) {
        $package_json_location = $project_directory . DIRECTORY_SEPARATOR . "package.json";
        $package_json_content = Files::getJson($package_json_location, []);
        $package_json_content = array_merge([
            "name" => null,
            "project" => null,
            "private" => null,
        ], $package_json_content);
        $project_name = $app_engine_project . '-' . $app_engine_service;
        $package_json_defaults["private"] = true;
        $package_json_content["name"] = $project_name;
        $package_json_content["project"] = $app_engine_project;
        foreach ($package_json_defaults as $key => $val) {
            $package_json_content[$key] = $val;
        }
        if ($app_engine_service == "default") {
            $package_json_content["scripts"]["deploy"] = 'gcloud app deploy app.yaml queue.yaml --project $npm_package_project --promote --quiet';
        } else {
            $package_json_content["scripts"]["deploy"] = 'gcloud app deploy app.yaml --project $npm_package_project --promote --quiet';
        }
        $gaeutil_json = Files::getJson(Conf::getGaeUtilJsonPath($project_directory), []);

        $project_key_name = $gaeutil_json[Secrets::CONF_PROJECT_KEY_NAME];
        $project_key = Secrets::reverseKmsKey($project_key_name);
        $crypt_params = [
            "ciphertext-file" => "config/secrets.cipher",
            "plaintext-file" => "secrets.json",
            "project" => $project_key["project"],
            "location" => $project_key["location"],
            "keyring" => $project_key["keyRing"],
            "key" => $project_key["cryptoKey"]
        ];
        $package_json_content["scripts"]["encrypt"] = self::commandMaker("gcloud kms encrypt", $crypt_params);
        $package_json_content["scripts"]["decrypt"] = self::commandMaker("gcloud kms decrypt", $crypt_params);
        $package_json_content["scripts"]["devserve"] = 'dev_appserver.py --port=5000 . -A $npm_package_project';
        if (Files::putJson($package_json_location, $package_json_content)) {
            Util::cmdline("Updated package.json in $project_name");
        }

    }
1278320
function(buffer, req, res, next) {
          var moduleDir = _.find(options.moduleDirs, function(dir) {
            return req.url.indexOf(options.root + dir) === 0;
          });

          // Only process JavaScript that are required modules, this means
          // bailing out early if not in the module path.
          if (!moduleDir || req.url.indexOf(options.root + "vendor") > 0) {
            return next();
          }

          // The module name is just the JavaScript file stripped of the
          // host and location.
          var moduleName = req.url.split(moduleDir)[1];
          moduleName = moduleName.slice(1);

          // I'd rather work with strings here, since buffers aren't widely
          // supported.
          buffer = String(buffer);

          // If ES6 modules are enabled in the configuration, convert by
          // default.
          if (options.es6) {
            buffer = new Compiler(buffer, moduleName.slice(-2, 0)).toAMD();
          }

          // This method allows hooking into the RequireJS toolchain.
          requirejs.tools.useLib(function(require) {
            // Convert to AMD if using CommonJS, by default the conversion
            // will ignore modules that already contain a define.
            require(["commonJs"], function(commonJs) {
              var wrapped = commonJs.convert(moduleName, buffer);
              var noDefine = wrapped.indexOf("define(") === -1;
              var noConfig = wrapped.indexOf("require.config") === -1;

              if (noDefine && noConfig) {
                wrapped = [
                  "define(function(require, exports, module) {",
                    wrapped,
                  "});"
                ].join("\n");
              }

              res.header("Content-type", "application/javascript");
              res.end(wrapped);
            });
          });
        }
1190150
function(next) {
            core.allowPackages.forEach(function(pkg) {
                try {
                    var mod = path.dirname(require.resolve(pkg)).replace(/\/lib$/, "");
                    core.packages[pkg] = { path: mod };
                    if (lib.statSync(mod + "/etc").isDirectory()) {
                        core.packages[pkg].etc = 1;
                        var cfg = lib.readFileSync(mod + "/etc/config");
                        if (cfg) {
                            config = cfg + "\n" + config;
                            core.packages[pkg].config = 1;
                            core.parseConfig(cfg, 1);
                        }
                    }
                    ["modules","locales","views","web"].forEach(function(x) {
                        if (lib.statSync(mod + "/" + x).isDirectory()) {
                            core.path[x].unshift(mod + "/" + x);
                            core.packages[pkg][x] = 1;
                        }
                    });
                    logger.debug("init:", "npm package:", pkg, core.packages[pkg]);
                } catch(e) {
                    logger.error("init:", "npm package:", pkg, e);
                }
            });
            next();
        }
453805
function loadPaths (pkg) {
  const name = pkg.name
  const file = pkg.path
  return resolveFile(tmp, path.join(name, file)).then(entry => ({
    entry: entry,
    package: path.join(tmp, 'node_modules', name, 'package.json')
  }))
}
1010085
function initNPM() {
    if (npmIsReady) return npmIsReady;

    npmIsReady = Promise.nfcall(npm.load, {
        silent: true,
        loglevel: 'silent'
    });

    return npmIsReady;
}
1216306
def _include_yaml(loader, node):
    
    return load_yaml(os.path.join(os.path.dirname(loader.name), node.value))
1026005
function (module_name, module_folder, callback) {
    var module_folder = path.resolve(module_folder)
    var module_packaged = _load_package(module_folder);

    var module_dependencies = _.d.get(module_packaged, "/dependencies");
    if (!module_dependencies) {
        return callback();
    }

    module_dependencies = _.keys(module_dependencies);

    var _install_next = function() {
        if (module_dependencies.length === 0) {
            return callback();
        }

        var dname = module_dependencies.pop();
        var dependency_folder = path.join(module_folder, "node_modules", dname);
        var dependency_homestard = _load_homestar(dependency_folder);

        var is_module = _.d.get(dependency_homestard, "/module", false);
        if (!is_module) {
            return _install_next();
        }

        console.log("- found dependency:", dname);
        _install(dname, function() {
            try {
                console.log("- cleanup");
                console.log("  path:", dependency_folder);
                _rmdirSync(dependency_folder);
            } catch (x) {
            }

            _install_next();
        });
    }

    _install_next();
}
15340
function addModulesToPackageJson(externalModules, packageJson, pathToPackageRoot) {
  _.forEach(externalModules, externalModule => {
    const splitModule = _.split(externalModule, '@');
    // If we have a scoped module we have to re-add the @
    if (_.startsWith(externalModule, '@')) {
      splitModule.splice(0, 1);
      splitModule[0] = '@' + splitModule[0];
    }
    let moduleVersion = _.join(_.tail(splitModule), '@');
    // We have to rebase file references to the target package.json
    moduleVersion = rebaseFileReferences(pathToPackageRoot, moduleVersion);
    packageJson.dependencies = packageJson.dependencies || {};
    packageJson.dependencies[_.first(splitModule)] = moduleVersion;
  });
}
887720
def build_module(name, doc=None):
    """"""
    node = nodes.Module(name, doc, pure_python=False)
    node.package = False
    node.parent = None
    return node
1255898
function resolvePackage(packageName) {
    try {
      // First, try to use require.resolve to find the package.
      // We add /package.json and then dirname the result because require.resolve follows the `main`
      // property in package.json to produce a path to a file deep inside the package, and we want
      // the path to the top-level directory.
      // This branch handles packages being symlinked into node_modules, for example with
      // `npm link` or in sku's test cases.
      const result = path.dirname(
        resolve(`${packageName}/package.json`, { paths: [cwd()] }),
      );
      debug(`Resolved ${packageName} to ${result}`);
      return result;
    } catch (error) {
      if (error.code === 'MODULE_NOT_FOUND') {
        const dependencies = getProjectDependencies(fs.readFileSync);

        if (!dependencies[packageName]) {
          // If it's not we can safely return a naive local path, which prevents webpack from
          // throwing config schema errors when this function is used to configure a loader.
          // This branch handles the scenario where we're trying to resolve a design system module because
          // it's in the default list of compilePackages, but it's not actually being used in the project.
          const localPackage = path.join(cwd(), 'node_modules', packageName);
          debug(`Resolved unused package ${packageName} to ${localPackage}`);
          return localPackage;
        }
      }

      // We've gotten this far because the package is listed as a project dependency and can't be
      // resolved, or because the error is not ENOENT. In either case we want to throw.
      throw error;
    }
  }