/*
A regular run of the mill require, but return null if the
module cannot be found.
423129
function(parentModule, id, callback) {

  // Try to load the module.
  return Promise.try(function() {
    return parentModule.require(id);
  })
  // Ignore module not found errors, and decorate all others.
  .catch(function(err) {
    if (err.code !== 'MODULE_NOT_FOUND') {
      throw new KboxRequireError(id, err);
    }
  })
  // Return.
  .nodeify(callback);

}
1148532
function(refPath) {
		var require = function(relModuleId) {
			var moduleId = resolveModuleId(relModuleId, refPath),
				module = getModule(moduleId);

			if (!module) {
				throw "Module not loaded";
			}
			else if (module.error) {
				throw "Error loading module";
			}

			if (!module.exports) {
				module.exports = {};
				var moduleDir = moduleId.substring(0, moduleId.lastIndexOf('/')+1),
					injects = module.injects,
					args = [];

				for (var i = 0, n = injects.length; i<n; i++) {
					if (injects[i] == 'require') {
						args.push(createRequireFunc(moduleDir));
					}
					else if (injects[i] == 'exports') {
						args.push(module.exports);
					}
					else if (injects[i] == 'module') {
						args.push(module.module);
					}
				}

				module.factory.apply(null, args);
			}
			return module.exports;
		};

		require.ensure = function(deps, cb) {
			ensureImpl(deps, cb, refPath);
		};

		if (_mainProgram != null) {
			require.main = getModule(_mainProgram).module;
		}

		return require;
	}
1110698
function modjewel_getModuleIdsRequired(moduleId) {
    var module = modjewel_getModule(moduleId)
    if (null == module) return null

    return module.moduleIdsRequired.slice()
}
1306704
function replaceRequire(code, codeDepth) {
    return code.replace(REG_REQUIRE, function ($0, $1, moduleId) {

        if (REG_DEP_MODULE.test(moduleId)) {
            moduleId = codeDepth + DEP_PARH + moduleId;
        }
        else if (REG_TOP_MODULE.test(moduleId)) {
            moduleId = codeDepth + moduleId;
        }
        return 'require(\'' + moduleId + '\')';
    });
}
1133091
function(parentModule, kbox, id, app, callback) {

  if (typeof callback === 'undefined' && typeof app === 'function') {
    callback = app;
    app = undefined;
  }

  // Try to load the module.
  return requireModule(parentModule, kbox, id, app)
  // If no module was loaded throw an error.
  .tap(function(mod) {
    if (!mod) {
      throw new Error('Cannot find module ' + id +
        ' try an npm install first.');
    }
  })
  // Handle different kinds of module initializations.
  .then(function(mod) {

    // Module was successfully loaded.
    if (typeof mod === 'object') {

      // Nothing extra needs to be done, just return module.
      return mod;

    } else if (typeof mod === 'function') {

      if (mod.length === 0) {

        // No arguments, so just execute function and return.
        return Promise.try(function() {
          return mod();
        })
        // Decorate any errors.
        .catch(function(err) {
          throw new KboxRequireError(id, err);
        });

      } else {

        // Argument names of the mod function.
        var args = inspect(mod);

        if (args.length === 1 && args[0] === 'kbox') {

          // Execute module function.
          return Promise.try(function() {
            return mod(kbox);
          })
          // Decorate any errors.
          .catch(function(err) {
            throw new KboxRequireError(id, err);
          });

        } else if (args.length === 2 &&
          args[0] === 'kbox' &&
          args[1] === 'app') {

          // Execute module function.
          return Promise.try(function() {
            return mod(kbox, app);
          })
          // Decorate any errors.
          .catch(function(err) {
            // Print a hopefully helpful warning for certain kinds of errors
            // @todo: this is pretty presumptuous and might be bad
            if (_.includes(err.message, 'Cannot read property')) {
              var warning = [
                'OH NO!',
                'It looks like something is wrong with your %s app named %s.',
                'We recommended purging this app and reinstalling it.',
                'This should help get it back into the correct state.'
              ];
              log.warn(format(warning.join(' '), id, app.name));
            }
            // Throw the error normally
            else {
              throw new KboxRequireError(id, err);
            }
          });

        } else {

          // Module function has an incorrect signature, throw an error.
          var funcString = mod.toString().split('\n')[0];
          throw new Error('Module "' + id + '" has an invalid ' +
            'signature. It was expected to be a function with a ' +
            'single argument of kbox, but instead it was: ' + funcString);

        }

      }

    } else {

      // This should never happen so assert fail if it does.
      assert.fail(undefined, undefined,
        'Required module expected to be either function or object');

    }

  })
  // Return.
  .nodeify(callback);

}
320128
function requireMethods(dir) {
  if (!dir) dir = getCallerDirname();

  var modules = {};

  fs
    .readdirSync(dir)
    .filter(function(filename) {
      return filename !== 'index.js';
    })
    .forEach(function(filename) {
      var filePath = path.join(dir, filename);
      var Stats = fs.lstatSync(filePath);
      var isLink = Stats.isSymbolicLink();
      var isDir = Stats.isDirectory();
      var isFile = Stats.isFile();
      var isJS = filename.indexOf('.js') > -1;

      if (!isLink && isDir) {
        modules[filename] = requireMethods(filePath);
      }

      else if (!isLink && isFile && isJS) {
        var entityName = filename.replace('.js', '');
        modules[entityName] = require(filePath);

        var hasES6Default = isObject(modules[entityName])
          && isFunction(modules[entityName].default);

        if (hasES6Default) {
          modules[entityName] = modules[entityName].default;
        }
      }
    });

  return modules;
}
648524
function(module) {
		var name = module.$modname;
		if (!this.$hasModule(name)) {
			this._modules.push(module);
			if (gui.Type.isFunction(module.oncontextinitialize)) {
				module.oncontextinitialize(window);
			}
			if (gui.Type.isFunction(module.onrun)) {
				module.onrun();
			}
		} else {
			throw new Error(name + ' loaded twice?');
		}
		return module;
	}
349513
@Nullable
  private Module getModuleFromScopeRoot(Node moduleBody) {
    if (moduleBody.isModuleBody()) {
      // TODO(b/128633181): handle ES modules here
      Node scriptNode = moduleBody.getParent();
      checkState(
          scriptNode.getBooleanProp(Node.GOOG_MODULE),
          "Typechecking of non-goog-modules not supported");
      Node googModuleCall = moduleBody.getFirstChild();
      String namespace = googModuleCall.getFirstChild().getSecondChild().getString();
      return moduleMap.getClosureModule(namespace);

    } else if (isGoogLoadModuleBlock(moduleBody)) {
      Node googModuleCall = moduleBody.getFirstChild();
      String namespace = googModuleCall.getFirstChild().getSecondChild().getString();
      return moduleMap.getClosureModule(namespace);
    }
    return null;
  }
853176
function findModulePath(request, parent) {
  var mainScriptDir = path.dirname(Module._resolveFilename(request, parent));
  var resolvedModule = Module._resolveLookupPaths(request, parent);
  var paths = resolvedModule[1];
  for (var i = 0, PL = paths.length; i < PL; i++) {
    if (mainScriptDir.indexOf(paths[i]) === 0) {
      return path.join(paths[i], request.replace('/', path.sep));
    }
  }
  return null;
}
176885
function requireNJS() {
  try {
    var module = ru(this.path);
  } catch(o_O) {
    console.error(o_O);
    return internalServerError.call(this, o_O);
  }
  module.onload(
    this.request,
    this.response,
    this
  );
}
530314
function getRequire(context, options, tag, type, resource) {
    const loaders = normalizeLoaders(options.map[type]);
    const selectLoader = require.resolve('./loader.js');
    const request = {
        tag,
        type,
        options
    };
    const url = loaderUtils.stringifyRequest(context, `!${loaders}!${selectLoader}?${JSON.stringify(request)}!${resource}`)
    const prefix = tag === 'script' ? 'module.exports = ' : 'const $style = ';
    return `${prefix}require(${url});\r\n`;
}
44179
function _require(dependency) {
        let result;
        try {
            result = require(path.join('ng-apimock', 'node_modules', dependency));
        } catch (ex) {
            result = require(dependency)
        }
        return result;
    }
1107835
function require(parent, id, fn) {
		if (fn) { return ensure(parent, id, fn); }
		var module = getModule(parent, id);
		if (!module.loaded) { throw new Error(id + ' not found'); }
		if (!('exports' in module)) {
			module.parent = parent; // first module to actually require this one is parent

			// if define was passed a non-function, just assign it to exports
			if ('function' !== typeof factories[id = module.id]) { module.exports = factories[id]; }
			else {
				module.exports = {};
				fn = map(module.children.slice(0, factories[id].length), // don't require prematurely on wrapped commonjs
						function(child) { return require(module, child.id); });
				if ((fn = factories[id].apply(global, fn))) { module.exports = fn; } // if something was returned, export it instead
			}
		}
		return module.exports;
	}
679947
function get() {
  if (!moduleManager && getDefault) {
    moduleManager = getDefault();
  }
  asserts.assert(
      moduleManager != null, 'The module manager has not yet been set.');
  return moduleManager;
}
457044
private void findModulesFromInput(
      CompilerInput input,
      boolean wasImportedByModule,
      Set<CompilerInput> inputs,
      Map<String, CompilerInput> inputsByIdentifier,
      Map<String, CompilerInput> inputsByProvide,
      boolean supportEs6Modules,
      boolean supportCommonJSModules) {
    if (!inputs.remove(input)) {
      // It's possible for a module to be included as both a script
      // and a module in the same compilation. In these cases, it should
      // be forced to be a module.
      if (wasImportedByModule && input.getJsModuleType() == CompilerInput.ModuleType.NONE) {
        input.setJsModuleType(CompilerInput.ModuleType.IMPORTED_SCRIPT);
      }
      return;
    }

    FindModuleDependencies findDeps =
        new FindModuleDependencies(
            this, supportEs6Modules, supportCommonJSModules, inputPathByWebpackId);
    findDeps.process(checkNotNull(input.getAstRoot(this)));

    // If this input was imported by another module, it is itself a module
    // so we force it to be detected as such.
    if (wasImportedByModule && input.getJsModuleType() == CompilerInput.ModuleType.NONE) {
      input.setJsModuleType(CompilerInput.ModuleType.IMPORTED_SCRIPT);
    }
    this.moduleTypesByName.put(input.getPath().toModuleName(), input.getJsModuleType());

    Iterable<String> allDeps =
        Iterables.concat(
            input.getRequiredSymbols(), input.getDynamicRequires(), input.getTypeRequires());
    for (String requiredNamespace : allDeps) {
      CompilerInput requiredInput = null;
      boolean requiredByModuleImport = false;
      if (inputsByProvide.containsKey(requiredNamespace)) {
        requiredInput = inputsByProvide.get(requiredNamespace);
      } else if (inputsByIdentifier.containsKey(requiredNamespace)) {
        requiredByModuleImport = true;
        requiredInput = inputsByIdentifier.get(requiredNamespace);
      }

      if (requiredInput != null) {
        findModulesFromInput(
            requiredInput,
            requiredByModuleImport,
            inputs,
            inputsByIdentifier,
            inputsByProvide,
            supportEs6Modules,
            supportCommonJSModules);
      }
    }
  }
1034235
function hasModule (name) {
    // throw error on invalid name
    requireValidName(name)
    // check if module exists
    return defined(immutable.modules[name]) ? true : false
}
1273301
function moduleLoaded(resolve, requires, modName, data, loadedModuleData, alreadyMinified){
    // Check for any modules used from this module that we don't already have
    var newRequires = getModulesRequired(data);
    console.log(" - "+modName+" requires "+JSON.stringify(newRequires));
    // if we need new modules, set them to load and get their promises
    var newPromises = [];
    for (var i in newRequires) {
      if (requires.indexOf(newRequires[i])<0) {
        console.log("   Queueing "+newRequires[i]);
        requires.push(newRequires[i]);
        newPromises.push(loadModule(requires, newRequires[i], loadedModuleData));
      } else {
        console.log("   Already loading "+newRequires[i]);
      }
    }

    var loadProcessedModule = function (module) {
      // add the module to the beginning of our array
      if (Espruino.Config.MODULE_AS_FUNCTION)
        loadedModuleData.unshift("Modules.addCached(" + JSON.stringify(module.name) + ",function(){" + module.code + "});");
      else
        loadedModuleData.unshift("Modules.addCached(" + JSON.stringify(module.name) + "," + JSON.stringify(module.code) + ");");
      // if we needed to load something, wait until we have all promises complete before resolving our promise!
      Promise.all(newPromises).then(function(){ resolve(); });
    }
    if (alreadyMinified)
      loadProcessedModule({code:data,name:modName});
    else
      Espruino.callProcessor("transformModuleForEspruino", {code:data,name:modName}, loadProcessedModule);
  }