ModuleBuilder.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #nullable enable
  2. using System;
  3. using System.Collections.Generic;
  4. using Esprima;
  5. using Esprima.Ast;
  6. using Jint.Native;
  7. using Jint.Runtime.Interop;
  8. using Jint.Runtime.Modules;
  9. namespace Jint;
  10. public sealed class ModuleBuilder
  11. {
  12. private readonly Engine _engine;
  13. private readonly List<string> _sourceRaw = new();
  14. private readonly Dictionary<string, JsValue> _exports = new();
  15. public ModuleBuilder(Engine engine)
  16. {
  17. _engine = engine;
  18. }
  19. public ModuleBuilder AddSource(string code)
  20. {
  21. _sourceRaw.Add(code);
  22. return this;
  23. }
  24. public ModuleBuilder ExportValue(string name, JsValue value)
  25. {
  26. _exports.Add(name, value);
  27. return this;
  28. }
  29. public ModuleBuilder ExportObject(string name, object value)
  30. {
  31. _exports.Add(name, JsValue.FromObject(_engine, value));
  32. return this;
  33. }
  34. public ModuleBuilder ExportType<T>()
  35. {
  36. ExportType<T>(typeof(T).Name);
  37. return this;
  38. }
  39. public ModuleBuilder ExportType<T>(string name)
  40. {
  41. _exports.Add(name, TypeReference.CreateTypeReference<T>(_engine));
  42. return this;
  43. }
  44. public ModuleBuilder ExportType(Type type)
  45. {
  46. ExportType(type.Name, type);
  47. return this;
  48. }
  49. public ModuleBuilder ExportType(string name, Type type)
  50. {
  51. _exports.Add(name, TypeReference.CreateTypeReference(_engine, type));
  52. return this;
  53. }
  54. public ModuleBuilder ExportFunction(string name, Func<JsValue[], JsValue> fn)
  55. {
  56. _exports.Add(name, new ClrFunctionInstance(_engine, name, (@this, args) => fn(args)));
  57. return this;
  58. }
  59. internal Module Parse()
  60. {
  61. if (_sourceRaw.Count > 0)
  62. {
  63. return new JavaScriptParser(_sourceRaw.Count == 1 ? _sourceRaw[0] : string.Join(Environment.NewLine, _sourceRaw)).ParseModule();
  64. }
  65. else
  66. {
  67. return new Module(NodeList.Create(Array.Empty<Statement>()));
  68. }
  69. }
  70. internal void BindExportedValues(JsModule module)
  71. {
  72. foreach (var export in _exports)
  73. {
  74. module.BindExportedValue(export.Key, export.Value);
  75. }
  76. }
  77. }