BuilderModule.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using Jint.Native;
  2. namespace Jint.Runtime.Modules;
  3. /// <summary>
  4. /// This is a custom ModuleRecord implementation for dynamically built modules using <see cref="ModuleBuilder"/>
  5. /// </summary>
  6. internal sealed class BuilderModule : SourceTextModule
  7. {
  8. private List<KeyValuePair<string, JsValue>> _exportBuilderDeclarations = new();
  9. internal BuilderModule(Engine engine, Realm realm, in Prepared<AstModule> source, string? location, bool async)
  10. : base(engine, realm, source, location, async)
  11. {
  12. }
  13. internal void BindExportedValue(string name, JsValue value)
  14. {
  15. if (_environment is not null)
  16. {
  17. Throw.InvalidOperationException("Cannot bind exported values after the environment has been initialized");
  18. }
  19. _exportBuilderDeclarations ??= new();
  20. _exportBuilderDeclarations.Add(new KeyValuePair<string, JsValue>(name, value));
  21. }
  22. protected override void InitializeEnvironment()
  23. {
  24. base.InitializeEnvironment();
  25. if (_exportBuilderDeclarations != null)
  26. {
  27. for (var i = 0; i < _exportBuilderDeclarations.Count; i++)
  28. {
  29. var d = _exportBuilderDeclarations[i];
  30. _environment.CreateImmutableBindingAndInitialize(d.Key, true, d.Value, DisposeHint.Normal);
  31. _localExportEntries.Add(new ExportEntry(d.Key, null, null, d.Key));
  32. }
  33. _exportBuilderDeclarations.Clear();
  34. }
  35. }
  36. }