DefaultModuleLoader.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. using Esprima;
  2. using Esprima.Ast;
  3. namespace Jint.Runtime.Modules;
  4. public sealed class DefaultModuleLoader : IModuleLoader
  5. {
  6. public delegate void ModuleLoadedEventHandler(object sender, string source, Module module);
  7. private readonly Uri _basePath;
  8. private readonly bool _restrictToBasePath;
  9. /// <summary>
  10. /// The Loaded event is triggered after a module is loaded and parsed.
  11. /// </summary>
  12. /// <remarks>
  13. /// The event is not triggered if a module was loaded but failed to parse.
  14. /// </remarks>
  15. public event ModuleLoadedEventHandler? Loaded;
  16. public DefaultModuleLoader(string basePath) : this(basePath, true)
  17. {
  18. }
  19. public DefaultModuleLoader(string basePath, bool restrictToBasePath)
  20. {
  21. if (string.IsNullOrWhiteSpace(basePath))
  22. {
  23. ExceptionHelper.ThrowArgumentException("Value cannot be null or whitespace.", nameof(basePath));
  24. }
  25. _restrictToBasePath = restrictToBasePath;
  26. if (!Uri.TryCreate(basePath, UriKind.Absolute, out _basePath))
  27. {
  28. if (!Path.IsPathRooted(basePath))
  29. {
  30. ExceptionHelper.ThrowArgumentException("Path must be rooted", nameof(basePath));
  31. }
  32. basePath = Path.GetFullPath(basePath);
  33. _basePath = new Uri(basePath, UriKind.Absolute);
  34. }
  35. if (_basePath.AbsolutePath[_basePath.AbsolutePath.Length - 1] != '/')
  36. {
  37. var uriBuilder = new UriBuilder(_basePath);
  38. uriBuilder.Path += '/';
  39. _basePath = uriBuilder.Uri;
  40. }
  41. }
  42. public ResolvedSpecifier Resolve(string? referencingModuleLocation, string specifier)
  43. {
  44. if (string.IsNullOrEmpty(specifier))
  45. {
  46. ExceptionHelper.ThrowModuleResolutionException("Invalid Module Specifier", specifier, referencingModuleLocation);
  47. return default;
  48. }
  49. // Specifications from ESM_RESOLVE Algorithm: https://nodejs.org/api/esm.html#resolution-algorithm
  50. Uri resolved;
  51. if (Uri.TryCreate(specifier, UriKind.Absolute, out var uri))
  52. {
  53. resolved = uri;
  54. }
  55. else if (IsRelative(specifier))
  56. {
  57. resolved = new Uri(referencingModuleLocation != null ? new Uri(referencingModuleLocation, UriKind.Absolute) : _basePath, specifier);
  58. }
  59. else if (specifier[0] == '#')
  60. {
  61. ExceptionHelper.ThrowNotSupportedException($"PACKAGE_IMPORTS_RESOLVE is not supported: '{specifier}'");
  62. return default;
  63. }
  64. else
  65. {
  66. return new ResolvedSpecifier(
  67. specifier,
  68. specifier,
  69. null,
  70. SpecifierType.Bare
  71. );
  72. }
  73. if (resolved.IsFile)
  74. {
  75. if (resolved.UserEscaped)
  76. {
  77. ExceptionHelper.ThrowModuleResolutionException("Invalid Module Specifier", specifier, referencingModuleLocation);
  78. return default;
  79. }
  80. if (!Path.HasExtension(resolved.LocalPath))
  81. {
  82. ExceptionHelper.ThrowModuleResolutionException("Unsupported Directory Import", specifier, referencingModuleLocation);
  83. return default;
  84. }
  85. }
  86. if (_restrictToBasePath && !_basePath.IsBaseOf(resolved))
  87. {
  88. ExceptionHelper.ThrowModuleResolutionException($"Unauthorized Module Path", specifier, referencingModuleLocation);
  89. return default;
  90. }
  91. return new ResolvedSpecifier(
  92. specifier,
  93. resolved.AbsoluteUri,
  94. resolved,
  95. SpecifierType.RelativeOrAbsolute
  96. );
  97. }
  98. public Module LoadModule(Engine engine, ResolvedSpecifier resolved)
  99. {
  100. if (resolved.Type != SpecifierType.RelativeOrAbsolute)
  101. {
  102. ExceptionHelper.ThrowNotSupportedException($"The default module loader can only resolve files. You can define modules directly to allow imports using {nameof(Engine)}.{nameof(Engine.AddModule)}(). Attempted to resolve: '{resolved.Specifier}'.");
  103. return default;
  104. }
  105. if (resolved.Uri == null)
  106. {
  107. ExceptionHelper.ThrowInvalidOperationException($"Module '{resolved.Specifier}' of type '{resolved.Type}' has no resolved URI.");
  108. }
  109. var fileName = Uri.UnescapeDataString(resolved.Uri.AbsolutePath);
  110. if (!File.Exists(fileName))
  111. {
  112. ExceptionHelper.ThrowArgumentException("Module Not Found: ", resolved.Specifier);
  113. return default;
  114. }
  115. var code = File.ReadAllText(fileName);
  116. var source = resolved.Uri.LocalPath;
  117. Module module;
  118. try
  119. {
  120. module = new JavaScriptParser().ParseModule(code, source);
  121. }
  122. catch (ParserException ex)
  123. {
  124. ExceptionHelper.ThrowSyntaxError(engine.Realm, $"Error while loading module: error in module '{source}': {ex.Error}");
  125. module = null;
  126. }
  127. catch (Exception)
  128. {
  129. ExceptionHelper.ThrowJavaScriptException(engine, $"Could not load module {source}", (Location) default);
  130. module = null;
  131. }
  132. Loaded?.Invoke(this, source, module);
  133. return module;
  134. }
  135. private static bool IsRelative(string specifier)
  136. {
  137. return specifier.StartsWith(".") || specifier.StartsWith("/");
  138. }
  139. }