Prefer importing modules from local node_modules (for NPX and global bin)
8379
async function _import(modulePath) {
  let m
  for (const mp of [ path.resolve(localNodeModules, modulePath), modulePath ]) {
    try {
      m = await import(mp)
    } catch (e) {
      /* istanbul ignore next */
      if (e.code !== 'MODULE_NOT_FOUND') {
        throw e
      } else if (mp === modulePath) {
        consola.fatal(
          `Module ${modulePath} not found.\n\n`,
          `Please install missing dependency:\n\n`,
          `Using npm:  npm i ${modulePath}\n\n`,
          `Using yarn: yarn add ${modulePath}`
        )
      }
    }
  }
  return m
}
735374
function resolve() {
	var parts,
		flg,
		len,
		str,
		i;

	// CASE 1: this module is loaded from a global path...
	len = gpaths.length;
	for ( i = 0; i < len; i++ ) {
		str = dir.substring( 0, gpaths[ i ].length );
		if ( str === gpaths[ i ] ) {
			// We are loaded from a global path. Resort to finding the nearest `package.json` walking up from the current working directory...
			str = pkgdir();
			if ( str ) {
				return str;
			}
			flg = true;
		}
	}
	// CASE 2: this module is a local module dependency; in which case, split on `node_modules`...
	parts = dir.split( path.sep+'node_modules' );
	if ( parts.length > 1 ) {
		// We are a nested module. Assume that the top-level node module directory is the application root...
		return parts[ 0 ];
	}
	// CASE 3: possibly a git submodule, copy and paste, or some other dependency pattern; in which case, find the nearest `package.json` walking up from the current working directory...
	if ( !flg ) {
		str = pkgdir();
		if ( str ) {
			return str;
		}
	}
	// CASE 4: nothing worked. Just use the main module...
	return path.dirname( require.main.filename );
}
848333
def FromImport(package_name, name_leafs):
    
    # XXX: May not handle dotted imports properly (eg, package_name='foo.bar')
    #assert package_name == '.' or '.' not in package_name, "FromImport has "\
    #       "not been tested with dotted package names -- use at your own "\
    #       "peril!"

    for leaf in name_leafs:
        # Pull the leaves out of their old tree
        leaf.remove()

    children = [Leaf(token.NAME, u"from"),
                Leaf(token.NAME, package_name, prefix=u" "),
                Leaf(token.NAME, u"import", prefix=u" "),
                Node(syms.import_as_names, name_leafs)]
    imp = Node(syms.import_from, children)
    return imp
1230327
def import_module(path):
    
    mod = __import__(path, locals={}, globals={})
    for item in path.split('.')[1:]:
        try:
            mod = getattr(mod, item)
        except AttributeError:
            raise ImportError('No module named %s' % path)
    return mod
924883
function init (options) {
  if (typeof options === 'string') {
    options = { base: options }
  }

  options = options || {}

  // There is probably 99% chance that the project root directory in located
  // above the node_modules directory
  var base = nodePath.resolve(
    options.base || nodePath.join(__dirname, '../..')
  )
  var packagePath = base.replace(/\/package\.json$/, '') + '/package.json'

  try {
    var npmPackage = require(packagePath)
  } catch (e) {
    // Do nothing
  }

  if (typeof npmPackage !== 'object') {
    throw new Error('Unable to read ' + packagePath)
  }

  //
  // Import aliases
  //

  var aliases = npmPackage._moduleAliases || {}

  for (var alias in aliases) {
    if (aliases[alias][0] !== '/') {
      aliases[alias] = nodePath.join(base, aliases[alias])
    }
  }

  addAliases(aliases)

  //
  // Register custom module directories (like node_modules)
  //

  if (npmPackage._moduleDirectories instanceof Array) {
    npmPackage._moduleDirectories.forEach(function (dir) {
      if (dir === 'node_modules') return

      var modulePath = nodePath.join(base, dir)
      addPath(modulePath)
    })
  }
}
287074
def load(self, root, module_path, pkg_name):
        
        root = os.path.join(root, module_path)
        import_name = os.path.join(pkg_name, module_path).replace(os.sep, '.')
        for (_, name, _) in pkgutil.iter_modules([root]):
            self.modules[name] = import_module('.' + name, package=import_name)
        return self.modules
1132792
def import_module(module):  # pylint: disable=R0201
        
        if isinstance(module, list):
            all_modules = module
        else:
            all_modules = [module]
        for mod in all_modules:
            globals()[mod] = __import__(mod.strip())
569449
def from_directory_import(
        self,
        module,
        real_names,
        local_names,
        import_alias_mapping,
        skip_init=False
    ):
        
        module_path = module[1]

        init_file_location = os.path.join(module_path, '__init__.py')
        init_exists = os.path.isfile(init_file_location)

        if init_exists and not skip_init:
            package_name = os.path.split(module_path)[1]
            return self.add_module(
                module=(module[0], init_file_location),
                module_or_package_name=package_name,
                local_names=local_names,
                import_alias_mapping=import_alias_mapping,
                is_init=True,
                from_from=True
            )
        for real_name in real_names:
            full_name = os.path.join(module_path, real_name)
            if os.path.isdir(full_name):
                new_init_file_location = os.path.join(full_name, '__init__.py')
                if os.path.isfile(new_init_file_location):
                    self.add_module(
                        module=(real_name, new_init_file_location),
                        module_or_package_name=real_name,
                        local_names=local_names,
                        import_alias_mapping=import_alias_mapping,
                        is_init=True,
                        from_from=True,
                        from_fdid=True
                    )
                else:
                    raise Exception('from anything import directory needs an __init__.py file in directory')
            else:
                file_module = (real_name, full_name + '.py')
                self.add_module(
                    module=file_module,
                    module_or_package_name=real_name,
                    local_names=local_names,
                    import_alias_mapping=import_alias_mapping,
                    from_from=True
                )
        return IgnoredNode()
793858
def visit_Import(self, node):
        """"""
        line = self._code_lines[node.lineno - 1]
        module_name = line.split("import")[0].strip()
        for name in node.names:
            imported_name = name.name
            if name.asname:
                imported_name = name.asname + "::" + imported_name
            self.imported_namespaces[imported_name] = module_name
174470
def _import_module(name, package='vlfd', warn=True, prefix='_py_', ignore='_'):
    
    import warnings
    from importlib import import_module
    try:
        try:
            module = import_module(name)
        except ImportError:
            module = import_module('.' + name, package=package)
    except ImportError:
        if warn:
            warnings.warn("failed to import module %s" % name)
    else:
        for attr in dir(module):
            if ignore and attr.startswith(ignore):
                continue
            if prefix:
                if attr in globals():
                    globals()[prefix + attr] = globals()[attr]
                elif warn:
                    warnings.warn("no Python implementation of " + attr)
            globals()[attr] = getattr(module, attr)
        return True
17795
def __push_import_modules(self):
        
        for module in self.__import_modules:
            sys.modules[module.__name__] = module
633625
def global_import(mod_name):
    
    mod_tuple = imp.find_module(mod_name, sys.path[1:])
    mod = imp.load_module(mod_name, mod_tuple[0], mod_tuple[1], mod_tuple[2])

    return mod
830620
def from_module_dict(cls, environment, module_dict, globals):
        
        return cls._from_namespace(environment, module_dict, globals)
1334017
def import_submodules(name, submodules=None):
    """"""
    sys.path.insert(0, name)
    if submodules:
        for submodule in submodules:
            import_string('{0}.{1}'.format(name, submodule))
    else:
        for item in pkgutil.walk_packages([name]):
            import_string('{0}.{1}'.format(name, item[1]))
657797
def _update_globals():
    

    if not sys.platform.startswith('java') and sys.platform != 'cli':
        return
    incompatible = 'extract_constant', 'get_module_constant'
    for name in incompatible:
        del globals()[name]
        __all__.remove(name)
523847
function resolveNodeModules(pkgpath) {
  let dir = pkgpath;
  let dirs = [];
  let depth = maxFileSystemDepth;
  let parent;
  let nodeModulespath;

  while (true) {
    parent = path.dirname(dir);
    // Stop if we hit max file system depth or root
    // Convert to lowercase to fix problems on Windows
    if (!--depth || parent.toLowerCase() === dir.toLowerCase()) {
      break;
    }

    nodeModulespath = path.resolve(dir, 'node_modules');

    if (exists(nodeModulespath)) dirs.push(nodeModulespath);

    // Walk
    dir = parent;
  }

  return dirs;
}
834351
def visit_Module(self, node):
        """"""
        self.generic_visit(node)
        import_alias = ast.alias(name='itertools', asname=mangle('itertools'))
        if self.use_itertools:
            importIt = ast.Import(names=[import_alias])
            node.body.insert(0, importIt)
        return node