Options.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Dynamic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Reflection;
  7. using Jint.Native;
  8. using Jint.Native.Object;
  9. using Jint.Runtime;
  10. using Jint.Runtime.Interop;
  11. using Jint.Runtime.Debugger;
  12. using Jint.Runtime.Descriptors;
  13. using Jint.Runtime.Interop.Reflection;
  14. using Jint.Runtime.References;
  15. namespace Jint
  16. {
  17. public delegate JsValue MemberAccessorDelegate(Engine engine, object target, string member);
  18. public sealed class Options
  19. {
  20. private readonly List<IConstraint> _constraints = new();
  21. private bool _strict;
  22. private DebuggerStatementHandling _debuggerStatementHandling;
  23. private bool _allowClr;
  24. private bool _allowClrWrite = true;
  25. private readonly List<IObjectConverter> _objectConverters = new();
  26. private Func<Engine, object, ObjectInstance> _wrapObjectHandler;
  27. private MemberAccessorDelegate _memberAccessor;
  28. private int _maxRecursionDepth = -1;
  29. private TimeSpan _regexTimeoutInterval = TimeSpan.FromSeconds(10);
  30. private CultureInfo _culture = CultureInfo.CurrentCulture;
  31. private TimeZoneInfo _localTimeZone = TimeZoneInfo.Local;
  32. private List<Assembly> _lookupAssemblies = new();
  33. private Predicate<Exception> _clrExceptionsHandler;
  34. private IReferenceResolver _referenceResolver = DefaultReferenceResolver.Instance;
  35. private readonly List<Action<Engine>> _configurations = new();
  36. private readonly List<Type> _extensionMethodClassTypes = new();
  37. internal ExtensionMethodCache _extensionMethods = ExtensionMethodCache.Empty;
  38. /// <summary>
  39. /// Run the script in strict mode.
  40. /// </summary>
  41. public Options Strict(bool strict = true)
  42. {
  43. _strict = strict;
  44. return this;
  45. }
  46. /// <summary>
  47. /// Selects the handling for script <code>debugger</code> statements.
  48. /// </summary>
  49. /// <remarks>
  50. /// The <c>debugger</c> statement can either be ignored (default) trigger debugging at CLR level (e.g. Visual Studio),
  51. /// or trigger a break in Jint's DebugHandler.
  52. /// </remarks>
  53. public Options DebuggerStatementHandling(DebuggerStatementHandling debuggerStatementHandling)
  54. {
  55. _debuggerStatementHandling = debuggerStatementHandling;
  56. return this;
  57. }
  58. /// <summary>
  59. /// Allow to run the script in debug mode.
  60. /// </summary>
  61. public Options DebugMode(bool debugMode = true)
  62. {
  63. IsDebugMode = debugMode;
  64. return this;
  65. }
  66. /// <summary>
  67. /// Adds a <see cref="IObjectConverter"/> instance to convert CLR types to <see cref="JsValue"/>
  68. /// </summary>
  69. public Options AddObjectConverter<T>() where T : IObjectConverter, new()
  70. {
  71. return AddObjectConverter(new T());
  72. }
  73. /// <summary>
  74. /// Adds a <see cref="IObjectConverter"/> instance to convert CLR types to <see cref="JsValue"/>
  75. /// </summary>
  76. public Options AddObjectConverter(IObjectConverter objectConverter)
  77. {
  78. _objectConverters.Add(objectConverter);
  79. return this;
  80. }
  81. public Options AddExtensionMethods(params Type[] types)
  82. {
  83. _extensionMethodClassTypes.AddRange(types);
  84. _extensionMethods = ExtensionMethodCache.Build(_extensionMethodClassTypes);
  85. return this;
  86. }
  87. private void AttachExtensionMethodsToPrototypes(Engine engine)
  88. {
  89. AttachExtensionMethodsToPrototype(engine, engine.Array.PrototypeObject, typeof(Array));
  90. AttachExtensionMethodsToPrototype(engine, engine.Boolean.PrototypeObject, typeof(bool));
  91. AttachExtensionMethodsToPrototype(engine, engine.Date.PrototypeObject, typeof(DateTime));
  92. AttachExtensionMethodsToPrototype(engine, engine.Number.PrototypeObject, typeof(double));
  93. AttachExtensionMethodsToPrototype(engine, engine.Object.PrototypeObject, typeof(ExpandoObject));
  94. AttachExtensionMethodsToPrototype(engine, engine.RegExp.PrototypeObject, typeof(System.Text.RegularExpressions.Regex));
  95. AttachExtensionMethodsToPrototype(engine, engine.String.PrototypeObject, typeof(string));
  96. }
  97. private void AttachExtensionMethodsToPrototype(Engine engine, ObjectInstance prototype, Type objectType)
  98. {
  99. if (!_extensionMethods.TryGetExtensionMethods(objectType, out var methods))
  100. {
  101. return;
  102. }
  103. foreach (var overloads in methods.GroupBy(x => x.Name))
  104. {
  105. var functionInstance = new MethodInfoFunctionInstance(engine, MethodDescriptor.Build(overloads.ToList()));
  106. var descriptor = new PropertyDescriptor(functionInstance, PropertyFlag.None);
  107. // make sure we register both lower case and upper case
  108. prototype.SetOwnProperty(overloads.Key, descriptor);
  109. if (char.IsUpper(overloads.Key[0]))
  110. {
  111. prototype.SetOwnProperty(char.ToLower(overloads.Key[0]) + overloads.Key.Substring(1), descriptor);
  112. }
  113. }
  114. }
  115. /// <summary>
  116. /// If no known type could be guessed, objects are normally wrapped as an
  117. /// ObjectInstance using class ObjectWrapper. This function can be used to
  118. /// register a handler for a customized handling.
  119. /// </summary>
  120. public Options SetWrapObjectHandler(Func<Engine, object, ObjectInstance> wrapObjectHandler)
  121. {
  122. _wrapObjectHandler = wrapObjectHandler;
  123. return this;
  124. }
  125. /// <summary>
  126. /// Sets the type converter to use.
  127. /// </summary>
  128. public Options SetTypeConverter(Func<Engine, ITypeConverter> typeConverterFactory)
  129. {
  130. _configurations.Add(engine => engine.ClrTypeConverter = typeConverterFactory(engine));
  131. return this;
  132. }
  133. /// <summary>
  134. /// Registers a delegate that is called when CLR members are invoked. This allows
  135. /// to change what values are returned for specific CLR objects, or if any value
  136. /// is returned at all.
  137. /// </summary>
  138. /// <param name="accessor">
  139. /// The delegate to invoke for each CLR member. If the delegate
  140. /// returns <c>null</c>, the standard evaluation is performed.
  141. /// </param>
  142. public Options SetMemberAccessor(MemberAccessorDelegate accessor)
  143. {
  144. _memberAccessor = accessor;
  145. return this;
  146. }
  147. /// <summary>
  148. /// Allows scripts to call CLR types directly like <example>System.IO.File</example>
  149. /// </summary>
  150. public Options AllowClr(params Assembly[] assemblies)
  151. {
  152. _allowClr = true;
  153. _lookupAssemblies.AddRange(assemblies);
  154. _lookupAssemblies = _lookupAssemblies.Distinct().ToList();
  155. return this;
  156. }
  157. public Options AllowClrWrite(bool allow = true)
  158. {
  159. _allowClrWrite = allow;
  160. return this;
  161. }
  162. /// <summary>
  163. /// Exceptions thrown from CLR code are converted to JavaScript errors and
  164. /// can be used in at try/catch statement. By default these exceptions are bubbled
  165. /// to the CLR host and interrupt the script execution.
  166. /// </summary>
  167. public Options CatchClrExceptions()
  168. {
  169. CatchClrExceptions(_ => true);
  170. return this;
  171. }
  172. /// <summary>
  173. /// Exceptions that thrown from CLR code are converted to JavaScript errors and
  174. /// can be used in at try/catch statement. By default these exceptions are bubbled
  175. /// to the CLR host and interrupt the script execution.
  176. /// </summary>
  177. public Options CatchClrExceptions(Predicate<Exception> handler)
  178. {
  179. _clrExceptionsHandler = handler;
  180. return this;
  181. }
  182. public Options Constraint(IConstraint constraint)
  183. {
  184. if (constraint != null)
  185. {
  186. _constraints.Add(constraint);
  187. }
  188. return this;
  189. }
  190. public Options WithoutConstraint(Predicate<IConstraint> predicate)
  191. {
  192. _constraints.RemoveAll(predicate);
  193. return this;
  194. }
  195. public Options RegexTimeoutInterval(TimeSpan regexTimeoutInterval)
  196. {
  197. _regexTimeoutInterval = regexTimeoutInterval;
  198. return this;
  199. }
  200. /// <summary>
  201. /// Sets maximum allowed depth of recursion.
  202. /// </summary>
  203. /// <param name="maxRecursionDepth">
  204. /// The allowed depth.
  205. /// a) In case max depth is zero no recursion is allowed.
  206. /// b) In case max depth is equal to n it means that in one scope function can be called no more than n times.
  207. /// </param>
  208. /// <returns>Options instance for fluent syntax</returns>
  209. public Options LimitRecursion(int maxRecursionDepth = 0)
  210. {
  211. _maxRecursionDepth = maxRecursionDepth;
  212. return this;
  213. }
  214. public Options Culture(CultureInfo cultureInfo)
  215. {
  216. _culture = cultureInfo;
  217. return this;
  218. }
  219. public Options LocalTimeZone(TimeZoneInfo timeZoneInfo)
  220. {
  221. _localTimeZone = timeZoneInfo;
  222. return this;
  223. }
  224. public Options SetReferencesResolver(IReferenceResolver resolver)
  225. {
  226. _referenceResolver = resolver;
  227. return this;
  228. }
  229. /// <summary>
  230. /// Registers some custom logic to apply on an <see cref="Engine"/> instance when the options
  231. /// are loaded.
  232. /// </summary>
  233. /// <param name="configuration">The action to register.</param>
  234. public Options Configure(Action<Engine> configuration)
  235. {
  236. _configurations.Add(configuration);
  237. return this;
  238. }
  239. /// <summary>
  240. /// Called by the <see cref="Engine"/> instance that loads this <see cref="Options" />
  241. /// once it is loaded.
  242. /// </summary>
  243. internal void Apply(Engine engine)
  244. {
  245. foreach (var configuration in _configurations)
  246. {
  247. configuration?.Invoke(engine);
  248. }
  249. // add missing bits if needed
  250. if (_allowClr)
  251. {
  252. engine.Global.SetProperty("System", new PropertyDescriptor(new NamespaceReference(engine, "System"), PropertyFlag.AllForbidden));
  253. engine.Global.SetProperty("importNamespace", new PropertyDescriptor(new ClrFunctionInstance(
  254. engine,
  255. "importNamespace",
  256. func: (thisObj, arguments) => new NamespaceReference(engine, TypeConverter.ToString(arguments.At(0)))), PropertyFlag.AllForbidden));
  257. }
  258. if (_extensionMethodClassTypes.Count > 0)
  259. {
  260. AttachExtensionMethodsToPrototypes(engine);
  261. }
  262. // ensure defaults
  263. engine.ClrTypeConverter ??= new DefaultTypeConverter(engine);
  264. }
  265. internal bool IsStrict => _strict;
  266. internal DebuggerStatementHandling _DebuggerStatementHandling => _debuggerStatementHandling;
  267. internal bool IsDebugMode { get; private set; }
  268. internal bool _IsClrWriteAllowed => _allowClrWrite;
  269. internal Predicate<Exception> _ClrExceptionsHandler => _clrExceptionsHandler;
  270. internal List<Assembly> _LookupAssemblies => _lookupAssemblies;
  271. internal List<IObjectConverter> _ObjectConverters => _objectConverters;
  272. internal List<IConstraint> _Constraints => _constraints;
  273. internal Func<Engine, object, ObjectInstance> _WrapObjectHandler => _wrapObjectHandler;
  274. internal MemberAccessorDelegate _MemberAccessor => _memberAccessor;
  275. internal int MaxRecursionDepth => _maxRecursionDepth;
  276. internal TimeSpan _RegexTimeoutInterval => _regexTimeoutInterval;
  277. internal CultureInfo _Culture => _culture;
  278. internal TimeZoneInfo _LocalTimeZone => _localTimeZone;
  279. internal IReferenceResolver ReferenceResolver => _referenceResolver;
  280. private sealed class DefaultReferenceResolver : IReferenceResolver
  281. {
  282. public static readonly DefaultReferenceResolver Instance = new DefaultReferenceResolver();
  283. private DefaultReferenceResolver()
  284. {
  285. }
  286. public bool TryUnresolvableReference(Engine engine, Reference reference, out JsValue value)
  287. {
  288. value = JsValue.Undefined;
  289. return false;
  290. }
  291. public bool TryPropertyReference(Engine engine, Reference reference, ref JsValue value)
  292. {
  293. return false;
  294. }
  295. public bool TryGetCallable(Engine engine, object callee, out JsValue value)
  296. {
  297. value = JsValue.Undefined;
  298. return false;
  299. }
  300. public bool CheckCoercible(JsValue value)
  301. {
  302. return false;
  303. }
  304. }
  305. }
  306. }