using Jint.Native;
using Jint.Native.Json;
namespace Jint.Runtime.Modules;
///
/// Factory which creates a single runtime from a given source.
///
public static class ModuleFactory
{
///
/// Creates a for the usage within the given
/// from the provided javascript .
///
///
/// The returned modules location (see ) points to
/// if is not null. If
/// is null, the modules location source will be null as well.
///
/// Is thrown if the provided can not be parsed.
/// Is thrown if an error occured when parsing .
public static Module BuildSourceTextModule(Engine engine, ResolvedSpecifier resolved, string code, ModuleParsingOptions? parsingOptions = null)
{
var source = resolved.Uri?.LocalPath ?? resolved.Key;
var parserOptions = (parsingOptions ?? ModuleParsingOptions.Default).GetParserOptions();
var parser = new Parser(parserOptions);
var module = parser.ParseModuleGuarded(engine, code, source);
return BuildSourceTextModule(engine, new Prepared(module, parserOptions));
}
///
/// Creates a for the usage within the given
/// from the parsed .
///
///
/// The returned modules location (see ) will be set
/// to of the .
///
public static Module BuildSourceTextModule(Engine engine, in Prepared preparedModule)
{
if (!preparedModule.IsValid)
{
Throw.InvalidPreparedModuleArgumentException(nameof(preparedModule));
}
return new SourceTextModule(engine, engine.Realm, preparedModule, preparedModule.Program!.Location.SourceFile, async: false);
}
///
/// Creates a for the usage within the given for the
/// provided JSON module .
///
///
/// The returned modules location (see ) points to
/// if is not null. If
/// is null, the modules location source will be null as well.
///
/// Is thrown if an error occured when parsing .
public static Module BuildJsonModule(Engine engine, ResolvedSpecifier resolved, string jsonString)
{
var source = resolved.Uri?.LocalPath;
JsValue module;
try
{
module = new JsonParser(engine).Parse(jsonString);
}
catch (Exception)
{
Throw.JavaScriptException(engine, $"Could not load module {source}", AstExtensions.DefaultLocation);
module = null;
}
return BuildJsonModule(engine, module, resolved.Uri?.LocalPath);
}
///
/// Creates a for the usage within the given
/// from the parsed JSON provided in .
///
///
/// The returned modules location (see ) will be set
/// to .
///
public static Module BuildJsonModule(Engine engine, JsValue parsedJson, string? location)
{
return new SyntheticModule(engine, engine.Realm, parsedJson, location);
}
}