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) { var source = resolved.Uri?.LocalPath ?? resolved.Key; Esprima.Ast.Module module; try { module = new Parser().ParseModule(code, source); } catch (ParseErrorException ex) { ExceptionHelper.ThrowSyntaxError(engine.Realm, $"Error while loading module: error in module '{source}': {ex.Error}"); module = null; } catch (Exception) { ExceptionHelper.ThrowJavaScriptException(engine, $"Could not load module {source}", (SourceLocation) default); module = null; } return BuildSourceTextModule(engine, module); } /// /// 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, Esprima.Ast.Module parsedModule) { return new SourceTextModule(engine, engine.Realm, parsedModule, parsedModule.Location.Source, 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) { ExceptionHelper.ThrowJavaScriptException(engine, $"Could not load module {source}", (SourceLocation) default); 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); } }