private static WrapperException WrapJsException(OriginalException originalException) { WrapperException wrapperException; string message = originalException.Message; string description = message; string type = originalException.Type; string documentName = originalException.Resource; int lineNumber = originalException.Line; int columnNumber = originalException.Column; if (originalException is OriginalInteropException) { wrapperException = new WrapperException(message, EngineName, EngineVersion, originalException); } else if (type == null && message.Equals(": at line: 0 column: 1.", StringComparison.Ordinal)) { wrapperException = new WrapperInterruptedException(CoreStrings.Runtime_ScriptInterrupted, EngineName, EngineVersion, originalException); } else { Match scriptErrorMessageMatch = _scriptErrorMessageRegex.Match(message); if (scriptErrorMessageMatch.Success) { WrapperScriptException wrapperScriptException; description = scriptErrorMessageMatch.Groups["description"].Value; message = JsErrorHelpers.GenerateScriptErrorMessage(type, description, documentName, lineNumber, columnNumber); if (type == JsErrorType.Syntax) { wrapperScriptException = new WrapperCompilationException(message, EngineName, EngineVersion, originalException); } else { wrapperScriptException = new WrapperRuntimeException(message, EngineName, EngineVersion, originalException); } wrapperScriptException.Type = type; wrapperScriptException.DocumentName = documentName; wrapperScriptException.LineNumber = lineNumber; wrapperScriptException.ColumnNumber = columnNumber; wrapperException = wrapperScriptException; } else { wrapperException = new WrapperException(message, EngineName, EngineVersion, originalException); } } wrapperException.Description = description; return(wrapperException); }
private static WrapperException WrapJavaScriptException( OriginalJavaScriptException originalJavaScriptException) { WrapperException wrapperException; string message = originalJavaScriptException.Message; if (string.IsNullOrWhiteSpace(message)) { message = "An unknown error occurred"; } string description = message; string type = string.Empty; string documentName = originalJavaScriptException.Location.Source; int lineNumber = originalJavaScriptException.LineNumber; int columnNumber = originalJavaScriptException.Column + 1; OriginalValue errorValue = originalJavaScriptException.Error; if (errorValue.IsObject()) { OriginalObjectInstance errorObject = errorValue.AsObject(); OriginalValue namePropertyValue = errorObject.Get("name"); if (namePropertyValue.IsString()) { type = namePropertyValue.AsString(); } } if (!string.IsNullOrEmpty(type)) { message = JsErrorHelpers.GenerateScriptErrorMessage(type, description, documentName, lineNumber, columnNumber); var wrapperRuntimeException = new WrapperRuntimeException(message, EngineName, EngineVersion, originalJavaScriptException) { Type = type, DocumentName = documentName, LineNumber = lineNumber, ColumnNumber = columnNumber }; wrapperException = wrapperRuntimeException; } else { wrapperException = new WrapperException(message, EngineName, EngineVersion, originalJavaScriptException); } wrapperException.Description = description; return(wrapperException); }
private static WrapperEngineLoadException WrapTypeLoadException( TypeLoadException originalTypeLoadException) { string originalMessage = originalTypeLoadException.Message; string description; string message; Match errorMessageMatch = _interfaceAssemblyLoadErrorMessage.Match(originalMessage); if (errorMessageMatch.Success) { string assemblyFileName = errorMessageMatch.Groups["assemblyFileName"].Value; var stringBuilderPool = StringBuilderPool.Shared; StringBuilder descriptionBuilder = stringBuilderPool.Rent(); descriptionBuilder.AppendFormat(CoreStrings.Engine_AssemblyNotFound, assemblyFileName); descriptionBuilder.Append(" "); if (assemblyFileName == DllName.V8LibCpp64Bit || assemblyFileName == DllName.V8LibCpp32Bit) { descriptionBuilder.AppendFormat(CoreStrings.Engine_NuGetPackageInstallationRequired, assemblyFileName == DllName.V8LibCpp64Bit ? "JavaScriptEngineSwitcher.V8.Native.win-x64" : "JavaScriptEngineSwitcher.V8.Native.win-x86" ); descriptionBuilder.Append(" "); descriptionBuilder.Append(Strings.Engine_VcRedist2017InstallationRequired); } else { descriptionBuilder.AppendFormat(CoreStrings.Common_SeeOriginalErrorMessage, originalMessage); } description = descriptionBuilder.ToString(); stringBuilderPool.Return(descriptionBuilder); message = JsErrorHelpers.GenerateEngineLoadErrorMessage(description, EngineName); } else { description = originalMessage; message = JsErrorHelpers.GenerateEngineLoadErrorMessage(description, EngineName, true); } var wrapperEngineLoadException = new WrapperEngineLoadException(message, EngineName, EngineVersion, originalTypeLoadException) { Description = description }; return(wrapperEngineLoadException); }
/// <summary> /// Constructs an instance of adapter for the V8 JS engine (Microsoft ClearScript.V8) /// </summary> /// <param name="settings">Settings of the V8 JS engine</param> public V8JsEngine(V8Settings settings) { V8Settings v8Settings = settings ?? new V8Settings(); var constraints = new OriginalRuntimeConstraints { HeapExpansionMultiplier = v8Settings.HeapExpansionMultiplier, MaxArrayBufferAllocation = v8Settings.MaxArrayBufferAllocation, MaxNewSpaceSize = v8Settings.MaxNewSpaceSize, MaxOldSpaceSize = v8Settings.MaxOldSpaceSize }; OriginalEngineFlags flags = OriginalEngineFlags.None; if (v8Settings.AwaitDebuggerAndPauseOnStart) { flags |= OriginalEngineFlags.AwaitDebuggerAndPauseOnStart; } if (v8Settings.EnableDebugging) { flags |= OriginalEngineFlags.EnableDebugging; } if (v8Settings.EnableRemoteDebugging) { flags |= OriginalEngineFlags.EnableRemoteDebugging; } if (v8Settings.DisableGlobalMembers) { flags |= OriginalEngineFlags.DisableGlobalMembers; } int debugPort = v8Settings.DebugPort; try { _jsEngine = new OriginalEngine(constraints, flags, debugPort) { MaxRuntimeHeapSize = v8Settings.MaxHeapSize, RuntimeHeapSizeSampleInterval = v8Settings.HeapSizeSampleInterval, MaxRuntimeStackUsage = v8Settings.MaxStackUsage }; } catch (TypeLoadException e) { throw WrapTypeLoadException(e); } catch (Exception e) { throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } }
/// <summary> /// "Cleans" CSS code by using Clean-css /// </summary> /// <param name="content">Text content of CSS asset</param> /// <param name="path">Path to CSS file</param> /// <returns>Minified text content of CSS asset</returns> public string Clean(string content, string path) { Initialize(); string newContent; try { var result = _jsEngine.Evaluate <string>( string.Format(CLEANING_FUNCTION_CALL_TEMPLATE, JsonConvert.SerializeObject(content), _optionsString)); var json = JObject.Parse(result); var errors = json["errors"] != null ? json["errors"] as JArray : null; if (errors != null && errors.Count > 0) { throw new CssCleaningException(FormatErrorDetails(errors[0].Value <string>(), true, path)); } if (_options.Severity > 0) { var warnings = json["warnings"] != null ? json["warnings"] as JArray : null; if (warnings != null && warnings.Count > 0) { throw new CssCleaningException(FormatErrorDetails(warnings[0].Value <string>(), false, path)); } } newContent = json.Value <string>("minifiedCode"); } catch (JsScriptException e) { string errorDetails = JsErrorHelpers.GenerateErrorDetails(e, true); var stringBuilderPool = StringBuilderPool.Shared; StringBuilder errorMessageBuilder = stringBuilderPool.Rent(); errorMessageBuilder.AppendLine(e.Message); errorMessageBuilder.AppendLine(); errorMessageBuilder.Append(errorDetails); string errorMessage = errorMessageBuilder.ToString(); stringBuilderPool.Return(errorMessageBuilder); throw new CssCleaningException(errorMessage); } return(newContent); }
/// <summary> /// Constructs an instance of adapter for the Jint JS engine /// </summary> /// <param name="settings">Settings of the Jint JS engine</param> public JintJsEngine(JintSettings settings) { _cancellationTokenSource = new CancellationTokenSource(); _cancellationConstraint = new OriginalCancellationConstraint(_cancellationTokenSource.Token); JintSettings jintSettings = settings ?? new JintSettings(); _debuggerBreakCallback = jintSettings.DebuggerBreakCallback; _debuggerStepCallback = jintSettings.DebuggerStepCallback; var debuggerStatementHandlingMode = Utils.GetEnumFromOtherEnum <JsDebuggerStatementHandlingMode, OriginalDebuggerStatementHandlingMode>( jintSettings.DebuggerStatementHandlingMode); try { _jsEngine = new OriginalEngine(options => { options .WithoutConstraint(c => c is OriginalCancellationConstraint) .Constraint(_cancellationConstraint) .DebuggerStatementHandling(debuggerStatementHandlingMode) .DebugMode(jintSettings.EnableDebugging) .LimitMemory(jintSettings.MemoryLimit) .LimitRecursion(jintSettings.MaxRecursionDepth) .LocalTimeZone(jintSettings.LocalTimeZone ?? TimeZoneInfo.Local) .MaxArraySize(jintSettings.MaxArraySize) .MaxStatements(jintSettings.MaxStatements) .Strict(jintSettings.StrictMode) .TimeoutInterval(jintSettings.TimeoutInterval) ; if (jintSettings.RegexTimeoutInterval.HasValue) { options.RegexTimeoutInterval(jintSettings.RegexTimeoutInterval.Value); } options.AddObjectConverter(new UndefinedConverter()); }); if (_debuggerBreakCallback != null) { _jsEngine.DebugHandler.Break += _debuggerBreakCallback; } if (_debuggerStepCallback != null) { _jsEngine.DebugHandler.Step += _debuggerStepCallback; } } catch (Exception e) { throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } }
private JsValue EvaluateModuleInternal(string code, string path, out JsValue moduleNamespace) { JsModuleRecord invalidModule = JsModuleRecord.Invalid; string modulePath = path; string moduleFullPath = GetModuleFullPath(invalidModule, modulePath); JsValue result; lock (_evaluationSynchronizer) { JsModuleRecord module = JsModuleRecord.Create(invalidModule, modulePath, moduleFullPath); module.SetFetchImportedModuleCallback(_fetchImportedModuleCallback); module.SetNotifyModuleReadyCallback(_notifyModuleReadyCallback); ModuleJob job = new ModuleJob { Module = module, Script = code, SourceUrl = moduleFullPath, IsParsed = false }; _moduleJobQueue.Enqueue(job); try { result = EvaluateModulesTree(out moduleNamespace); JsValue exception = module.Exception; if (exception.IsValid) { JsValue metadata = JsValue.Invalid; if (!JsContext.HasException) { JsErrorHelpers.SetException(exception); } metadata = JsContext.GetAndClearExceptionWithMetadata(); throw JsErrorHelpers.CreateScriptExceptionFromMetadata(metadata); } } finally { _moduleJobQueue.Clear(); module.Release(); } } return(result); }
private static WrapperRuntimeException WrapMemoryLimitExceededException( OriginalMemoryLimitExceededException originalMemoryException) { string description = originalMemoryException.Message; string type = JsErrorType.Common; string message = JsErrorHelpers.GenerateScriptErrorMessage(type, description, string.Empty); var wrapperRuntimeException = new WrapperRuntimeException(message, EngineName, EngineVersion, originalMemoryException) { Description = description }; return(wrapperRuntimeException); }
private static WrapperRuntimeException WrapStatementsCountOverflowException( OriginalStatementsCountOverflowException originalStatementsException) { string description = originalStatementsException.Message; string type = JsErrorType.Range; string message = JsErrorHelpers.GenerateScriptErrorMessage(type, description, string.Empty); var wrapperRuntimeException = new WrapperRuntimeException(message, EngineName, EngineVersion, originalStatementsException) { Description = description }; return(wrapperRuntimeException); }
private static WrapperRuntimeException WrapRecursionDepthOverflowException( OriginalRecursionDepthOverflowException originalRecursionException) { string callStack = string.Empty; string[] callChainItems = originalRecursionException.CallChain .Split(new string[] { "->" }, StringSplitOptions.None) ; if (callChainItems.Length > 0) { var stringBuilderPool = StringBuilderPool.Shared; StringBuilder stackBuilder = stringBuilderPool.Rent(); for (int chainItemIndex = callChainItems.Length - 1; chainItemIndex >= 0; chainItemIndex--) { string chainItem = callChainItems[chainItemIndex]; if (chainItem == "anonymous function") { chainItem = "Anonymous function"; } JsErrorHelpers.WriteErrorLocationLine(stackBuilder, chainItem, string.Empty, 0, 0); if (chainItemIndex > 0) { stackBuilder.AppendLine(); } } callStack = stackBuilder.ToString(); stringBuilderPool.Return(stackBuilder); } string description = originalRecursionException.Message; string type = JsErrorType.Range; string message = JsErrorHelpers.GenerateScriptErrorMessage(type, description, callStack); var wrapperRuntimeException = new WrapperRuntimeException(message, EngineName, EngineVersion, originalRecursionException) { Description = description, Type = type, CallStack = callStack }; return(wrapperRuntimeException); }
private static WrapperEngineLoadException WrapTypeLoadException( TypeLoadException originalTypeLoadException) { string originalMessage = originalTypeLoadException.Message; string description; string message; Match errorMessageMatch = _libraryLoadErrorMessage.Match(originalMessage); if (errorMessageMatch.Success) { string assemblyFileName = errorMessageMatch.Groups["assemblyFileName"].Value; var stringBuilderPool = StringBuilderPool.Shared; StringBuilder descriptionBuilder = stringBuilderPool.Rent(); descriptionBuilder.AppendFormat(CoreStrings.Engine_AssemblyNotFound, assemblyFileName); descriptionBuilder.Append(" "); string packageName; if (_nativeAssemblyPackageMap.TryGetValue(assemblyFileName, out packageName)) { descriptionBuilder.AppendFormat(CoreStrings.Engine_NuGetPackageInstallationRequired, packageName); } else { descriptionBuilder.AppendFormat(CoreStrings.Common_SeeOriginalErrorMessage, originalMessage); } description = descriptionBuilder.ToString(); stringBuilderPool.Return(descriptionBuilder); message = JsErrorHelpers.GenerateEngineLoadErrorMessage(description, EngineName); } else { description = originalMessage; message = JsErrorHelpers.GenerateEngineLoadErrorMessage(description, EngineName, true); } var wrapperEngineLoadException = new WrapperEngineLoadException(message, EngineName, EngineVersion, originalTypeLoadException) { Description = description }; return(wrapperEngineLoadException); }
/// <summary> /// "Compiles" a TypeScript code to JS code /// </summary> /// <param name="path">Path to TypeScript file</param> /// <returns>Compilation result</returns> public CompilationResult Compile(string path) { Initialize(); CompilationResult compilationResult; try { var result = _jsEngine.Evaluate <string>(string.Format(COMPILATION_FUNCTION_CALL_TEMPLATE, JsonConvert.SerializeObject(path), _optionsString)); var json = JObject.Parse(result); var errors = json["errors"] != null ? json["errors"] as JArray : null; if (errors != null && errors.Count > 0) { throw new TypeScriptCompilationException(FormatErrorDetails(errors[0], path)); } compilationResult = new CompilationResult { CompiledContent = json.Value <string>("compiledCode"), IncludedFilePaths = json.Value <JArray>("includedFilePaths") .ToObject <IList <string> >() .Distinct(StringComparer.OrdinalIgnoreCase) .Where(p => !p.Equals(path, StringComparison.OrdinalIgnoreCase)) .ToList() }; } catch (JsScriptException e) { string errorDetails = JsErrorHelpers.GenerateErrorDetails(e, true); var stringBuilderPool = StringBuilderPool.Shared; StringBuilder errorMessageBuilder = stringBuilderPool.Rent(); errorMessageBuilder.AppendLine(e.Message); errorMessageBuilder.AppendLine(); errorMessageBuilder.Append(errorDetails); string errorMessage = errorMessageBuilder.ToString(); stringBuilderPool.Return(errorMessageBuilder); throw new TypeScriptCompilationException(errorMessage); } return(compilationResult); }
/// <summary> /// "Compiles" Handlebars template to JS code /// </summary> /// <param name="content">Text content of Handlebars template</param> /// <param name="path">Path to Handlebars file</param> /// <returns>Translated Handlebars template</returns> public string Compile(string content, string path) { Initialize(); string newContent; try { var result = _jsEngine.Evaluate <string>( string.Format(COMPILATION_FUNCTION_CALL_TEMPLATE, JsonConvert.SerializeObject(content), _optionsString)); var json = JObject.Parse(result); var errors = json["errors"] != null ? json["errors"] as JArray : null; if (errors != null && errors.Count > 0) { throw new HandlebarsCompilationException(FormatErrorDetails(errors[0], content, path)); } var compiledCode = json.Value <string>("compiledCode"); bool isPartial; string templateName = GetTemplateName(path, _options.RootPath, out isPartial); newContent = WrapCompiledTemplateCode(compiledCode, _options.Namespace, templateName, isPartial); } catch (JsScriptException e) { string errorDetails = JsErrorHelpers.GenerateErrorDetails(e, true); var stringBuilderPool = StringBuilderPool.Shared; StringBuilder errorMessageBuilder = stringBuilderPool.Rent(); errorMessageBuilder.AppendLine(e.Message); errorMessageBuilder.AppendLine(); errorMessageBuilder.Append(errorDetails); string errorMessage = errorMessageBuilder.ToString(); stringBuilderPool.Return(errorMessageBuilder); throw new HandlebarsCompilationException(errorMessage); } return(newContent); }
/// <summary> /// "Packs" a JS code by using Dean Edwards' Packer /// </summary> /// <param name="content">Text content of JS asset</param> /// <returns>Minified text content of JS asset</returns> public string Pack(string content) { Initialize(); string newContent; try { newContent = _jsEngine.CallFunction <string>(PACKING_FUNCTION_NAME, content, _options.Base62Encode, _options.ShrinkVariables); } catch (JsRuntimeException e) { throw new JsPackingException(JsErrorHelpers.Format(e)); } return(newContent); }
/// <summary> /// Actualizes a vendor prefixes in CSS code by using Andrey Sitnik's Autoprefixer /// </summary> /// <param name="content">Text content of CSS asset</param> /// <param name="path">Path to CSS asset</param> /// <returns>Autoprefixing result</returns> public AutoprefixingResult Process(string content, string path) { Initialize(); AutoprefixingResult autoprefixingResult; try { var result = _jsEngine.Evaluate <string>( string.Format(AUTOPREFIXING_FUNCTION_CALL_TEMPLATE, JsonConvert.SerializeObject(content), _optionsString)); var json = JObject.Parse(result); var errors = json["errors"] != null ? json["errors"] as JArray : null; if (errors != null && errors.Count > 0) { throw new CssAutoprefixingException(FormatErrorDetails(errors[0], content, path)); } autoprefixingResult = new AutoprefixingResult { ProcessedContent = json.Value <string>("processedCode"), IncludedFilePaths = GetIncludedFilePaths(_options.Stats) }; } catch (JsScriptException e) { string errorDetails = JsErrorHelpers.GenerateErrorDetails(e, true); var stringBuilderPool = StringBuilderPool.Shared; StringBuilder errorMessageBuilder = stringBuilderPool.Rent(); errorMessageBuilder.AppendLine(e.Message); errorMessageBuilder.AppendLine(); errorMessageBuilder.Append(errorDetails); string errorMessage = errorMessageBuilder.ToString(); stringBuilderPool.Return(errorMessageBuilder); throw new CssAutoprefixingException(errorMessage); } return(autoprefixingResult); }
public static string UnmaskFrom(string maskedUrl, string userId) { try { using (var jsEngine = new MsieJsEngine()) { jsEngine.ExecuteResource("VkAudioSync.Vk.audioUnmask.js", Assembly.GetExecutingAssembly()); return(jsEngine.Evaluate <string>($"unmaskUrl(\"{maskedUrl}\", {userId});")); } } catch (JsEngineLoadException e) { throw new Exception($"JS Compile error: {JsErrorHelpers.Format(e)}"); } catch (JsRuntimeException e) { throw new Exception($"JS Runtime error: {JsErrorHelpers.Format(e)}"); } }
/// <summary> /// Constructs an instance of adapter for the Vroom JS engine /// (cross-platform bridge to the V8 JS engine) /// </summary> /// <param name="settings">Settings of the Vroom JS engine</param> public VroomJsEngine(VroomSettings settings) { Initialize(); VroomSettings vroomSettings = settings ?? new VroomSettings(); try { _jsEngine = new OriginalEngine(vroomSettings.MaxYoungSpaceSize, vroomSettings.MaxOldSpaceSize); _jsContext = _jsEngine.CreateContext(); } catch (TypeInitializationException e) { Exception innerException = e.InnerException; if (innerException != null) { var dllNotFoundException = innerException as DllNotFoundException; if (dllNotFoundException != null) { throw WrapDllNotFoundException(dllNotFoundException); } else { throw JsErrorHelpers.WrapEngineLoadException(innerException, EngineName, EngineVersion, true); } } throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } catch (Exception e) { throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } finally { if (_jsContext == null) { Dispose(); } } }
/// <summary> /// Constructs an instance of adapter for the NiL JS engine /// </summary> /// <param name="settings">Settings of the NiL JS engine</param> public NiLJsEngine(NiLSettings settings) { NiLSettings niLSettings = settings ?? new NiLSettings(); _debuggerCallback = niLSettings.DebuggerCallback; try { _jsContext = new OriginalContext(niLSettings.StrictMode); _jsContext.Debugging = niLSettings.EnableDebugging; if (_debuggerCallback != null) { _jsContext.DebuggerCallback += _debuggerCallback; } } catch (Exception e) { throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } }
/// <summary> /// Constructs an instance of adapter for the Jurassic JS engine /// </summary> /// <param name="settings">Settings of the Jurassic JS engine</param> public JurassicJsEngine(JurassicSettings settings) { JurassicSettings jurassicSettings = settings ?? new JurassicSettings(); try { _jsEngine = new OriginalEngine { CompatibilityMode = OriginalCompatibilityMode.Latest, DisableClrCollectionsExposingByValue = !jurassicSettings.EnableHostCollectionsEmbeddingByValue, EnableExposedClrTypes = true, EnableILAnalysis = jurassicSettings.EnableIlAnalysis, ForceStrictMode = jurassicSettings.StrictMode }; } catch (Exception e) { throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } }
/// <summary> /// "Compiles" CoffeeScript code to JS code /// </summary> /// <param name="content">Text content written on CoffeeScript</param> /// <param name="path">Path to CoffeeScript file</param> /// <returns>Translated CoffeeScript code</returns> public string Compile(string content, string path) { Initialize(); string newContent; string optionsString = ConvertCompilationOptionsToJson(path, _options).ToString(); try { var result = _jsEngine.Evaluate <string>( string.Format(COMPILATION_FUNCTION_CALL_TEMPLATE, JsonConvert.SerializeObject(content), optionsString)); var json = JObject.Parse(result); var errors = json["errors"] != null ? json["errors"] as JArray : null; if (errors != null && errors.Count > 0) { throw new CoffeeScriptCompilationException(FormatErrorDetails(errors[0], content, path)); } newContent = json.Value <string>("compiledCode"); } catch (JsScriptException e) { string errorDetails = JsErrorHelpers.GenerateErrorDetails(e, true); var stringBuilderPool = StringBuilderPool.Shared; StringBuilder errorMessageBuilder = stringBuilderPool.Rent(); errorMessageBuilder.AppendLine(e.Message); errorMessageBuilder.AppendLine(); errorMessageBuilder.Append(errorDetails); string errorMessage = errorMessageBuilder.ToString(); stringBuilderPool.Return(errorMessageBuilder); throw new CoffeeScriptCompilationException(errorMessage); } return(newContent); }
private static WrapperCompilationException WrapSyntaxException( OriginalSyntaxException originalSyntaxException) { string description = originalSyntaxException.Message; string type = JsErrorType.Syntax; string documentName = originalSyntaxException.SourcePath; int lineNumber = originalSyntaxException.LineNumber; string message = JsErrorHelpers.GenerateScriptErrorMessage(type, description, documentName, lineNumber, 0); var wrapperCompilationException = new WrapperCompilationException(message, EngineName, EngineVersion, originalSyntaxException) { Description = description, Type = type, DocumentName = documentName, LineNumber = lineNumber }; return(wrapperCompilationException); }
/// <summary> /// Constructs an instance of adapter for the Jint JS engine /// </summary> /// <param name="settings">Settings of the Jint JS engine</param> public JintJsEngine(JintSettings settings) { JintSettings jintSettings = settings ?? new JintSettings(); try { _jsEngine = new OriginalEngine(c => c .AllowDebuggerStatement(jintSettings.AllowDebuggerStatement) .DebugMode(jintSettings.EnableDebugging) .LimitRecursion(jintSettings.MaxRecursionDepth) .LocalTimeZone(jintSettings.LocalTimeZone ?? TimeZoneInfo.Local) .MaxStatements(jintSettings.MaxStatements) .Strict(jintSettings.StrictMode) .TimeoutInterval(jintSettings.TimeoutInterval) ); } catch (Exception e) { throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } }
/// <summary> /// "Cleans" CSS code by using Clean-css /// </summary> /// <param name="content">Text content of CSS asset</param> /// <param name="path">Path to CSS file</param> /// <returns>Minified text content of CSS asset</returns> public string Clean(string content, string path) { Initialize(); string newContent; try { var result = _jsEngine.Evaluate <string>( string.Format(CLEANING_FUNCTION_CALL_TEMPLATE, JsonConvert.SerializeObject(content), _optionsString)); var json = JObject.Parse(result); var errors = json["errors"] != null ? json["errors"] as JArray : null; if (errors != null && errors.Count > 0) { throw new CssCleaningException(FormatErrorDetails(errors[0].Value <string>(), true, path)); } if (_options.Severity > 0) { var warnings = json["warnings"] != null ? json["warnings"] as JArray : null; if (warnings != null && warnings.Count > 0) { throw new CssCleaningException(FormatErrorDetails(warnings[0].Value <string>(), false, path)); } } newContent = json.Value <string>("minifiedCode"); } catch (JsRuntimeException e) { throw new CssCleaningException(JsErrorHelpers.Format(e)); } return(newContent); }
/// <summary> /// Constructs an instance of adapter for the Jurassic JS engine /// </summary> /// <param name="settings">Settings of the Jurassic JS engine</param> public JurassicJsEngine(JurassicSettings settings) { JurassicSettings jurassicSettings = settings ?? new JurassicSettings(); try { _jsEngine = new OriginalEngine { #if !NETSTANDARD2_0 EnableDebugging = jurassicSettings.EnableDebugging, #endif CompatibilityMode = OriginalCompatibilityMode.Latest, EnableExposedClrTypes = true, EnableILAnalysis = jurassicSettings.EnableIlAnalysis, ForceStrictMode = jurassicSettings.StrictMode }; } catch (Exception e) { throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } }
private static WrapperCompilationException WrapParserException(OriginalParserException originalParserException) { string description = originalParserException.Description; string type = JsErrorType.Syntax; string documentName = originalParserException.SourceText; int lineNumber = originalParserException.LineNumber; int columnNumber = originalParserException.Column; string message = JsErrorHelpers.GenerateScriptErrorMessage(type, description, documentName, lineNumber, columnNumber); var wrapperCompilationException = new WrapperCompilationException(message, EngineName, EngineVersion, originalParserException) { Description = description, Type = type, DocumentName = documentName, LineNumber = lineNumber, ColumnNumber = columnNumber }; return(wrapperCompilationException); }
/// <summary> /// "Compiles" a TypeScript code to JS code /// </summary> /// <param name="path">Path to TypeScript file</param> /// <returns>Compilation result</returns> public CompilationResult Compile(string path) { Initialize(); CompilationResult compilationResult; try { var result = _jsEngine.Evaluate <string>(string.Format(COMPILATION_FUNCTION_CALL_TEMPLATE, JsonConvert.SerializeObject(path), _optionsString)); var json = JObject.Parse(result); var errors = json["errors"] != null ? json["errors"] as JArray : null; if (errors != null && errors.Count > 0) { throw new TypeScriptCompilationException(FormatErrorDetails(errors[0], path)); } compilationResult = new CompilationResult { CompiledContent = json.Value <string>("compiledCode"), IncludedFilePaths = json.Value <JArray>("includedFilePaths") .ToObject <IList <string> >() .Distinct(StringComparer.OrdinalIgnoreCase) .Where(p => !p.Equals(path, StringComparison.OrdinalIgnoreCase)) .ToList() }; } catch (JsRuntimeException e) { throw new TypeScriptCompilationException(JsErrorHelpers.Format(e)); } return(compilationResult); }
/// <summary> /// Returns a string that represents the current exception /// </summary> /// <returns>A string that represents the current exception</returns> public override string ToString() { string errorDetails = JsErrorHelpers.GenerateErrorDetails(this, true); var stringBuilderPool = StringBuilderPool.Shared; StringBuilder resultBuilder = stringBuilderPool.Rent(); resultBuilder.Append(this.GetType().FullName); resultBuilder.Append(": "); resultBuilder.Append(this.Message); if (errorDetails.Length > 0) { resultBuilder.AppendLine(); resultBuilder.AppendLine(); resultBuilder.Append(errorDetails); } if (this.InnerException != null) { resultBuilder.Append(" ---> "); resultBuilder.Append(this.InnerException.ToString()); } if (this.StackTrace != null) { resultBuilder.AppendLine(); resultBuilder.AppendLine(this.StackTrace); } string result = resultBuilder.ToString(); stringBuilderPool.Return(resultBuilder); return(result); }
/// <summary> /// Constructs an instance of adapter for the Jint JS engine /// </summary> /// <param name="settings">Settings of the Jint JS engine</param> public JintJsEngine(JintSettings settings) { _cancellationTokenSource = new CancellationTokenSource(); _cancellationConstraint = new OriginalCancellationConstraint(_cancellationTokenSource.Token); JintSettings jintSettings = settings ?? new JintSettings(); try { _jsEngine = new OriginalEngine(options => { options .AllowDebuggerStatement(jintSettings.AllowDebuggerStatement) .WithoutConstraint(c => c is OriginalCancellationConstraint) .Constraint(_cancellationConstraint) .DebugMode(jintSettings.EnableDebugging) .LimitMemory(jintSettings.MemoryLimit) .LimitRecursion(jintSettings.MaxRecursionDepth) .LocalTimeZone(jintSettings.LocalTimeZone ?? TimeZoneInfo.Local) .MaxStatements(jintSettings.MaxStatements) .Strict(jintSettings.StrictMode) .TimeoutInterval(jintSettings.TimeoutInterval) ; if (jintSettings.RegexTimeoutInterval.HasValue) { options.RegexTimeoutInterval(jintSettings.RegexTimeoutInterval.Value); } options.AddObjectConverter(new UndefinedConverter()); }); } catch (Exception e) { throw JsErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } }
private JsValue CreateFunctionFromDelegate(Delegate value) { JsNativeFunction nativeFunction = (callee, isConstructCall, args, argCount, callbackData) => { object[] processedArgs = MapToHostType(args.Skip(1).ToArray()); ParameterInfo[] parameters = value.GetMethodInfo().GetParameters(); JsValue undefinedValue = JsValue.Undefined; ReflectionHelpers.FixArgumentTypes(ref processedArgs, parameters); object result; try { result = value.DynamicInvoke(processedArgs); } catch (Exception e) { JsValue errorValue = JsErrorHelpers.CreateError( string.Format(Strings.Runtime_HostDelegateInvocationFailed, e.Message)); JsErrorHelpers.SetException(errorValue); return(undefinedValue); } JsValue resultValue = MapToScriptType(result); return(resultValue); }; _nativeFunctions.Add(nativeFunction); JsValue functionValue = JsValue.CreateFunction(nativeFunction); return(functionValue); }
private static WrapperException WrapJsException(OriginalException originalException) { WrapperException wrapperException; string message = originalException.Message; string description = message; string type = string.Empty; int lineNumber = 0; int columnNumber = 0; string sourceFragment = string.Empty; var errorValue = originalException.Error?.Value as OriginalError; if (errorValue != null) { message = errorValue.message.As <string>(); description = message; type = errorValue.name.As <string>(); } if (!string.IsNullOrEmpty(type)) { WrapperScriptException wrapperScriptException; if (type == JsErrorType.Syntax) { Match messageMatch = _syntaxErrorMessageRegex.Match(message); if (messageMatch.Success) { GroupCollection messageGroups = messageMatch.Groups; description = messageGroups["description"].Value; lineNumber = int.Parse(messageGroups["lineNumber"].Value); columnNumber = int.Parse(messageGroups["columnNumber"].Value); } message = JsErrorHelpers.GenerateScriptErrorMessage(type, description, string.Empty, lineNumber, columnNumber); wrapperScriptException = new WrapperCompilationException(message, EngineName, EngineVersion, originalException); } else { string sourceCode = originalException.Code; OriginalCodeCoordinates codeCoordinates = originalException.CodeCoordinates; if (codeCoordinates != null) { lineNumber = codeCoordinates.Line; columnNumber = codeCoordinates.Column; } sourceFragment = TextHelpers.GetTextFragment(sourceCode, lineNumber, columnNumber); message = JsErrorHelpers.GenerateScriptErrorMessage(type, description, string.Empty, lineNumber, columnNumber, sourceFragment); wrapperScriptException = new WrapperRuntimeException(message, EngineName, EngineVersion, originalException); } wrapperScriptException.Type = type; wrapperScriptException.LineNumber = lineNumber; wrapperScriptException.ColumnNumber = columnNumber; wrapperScriptException.SourceFragment = sourceFragment; wrapperException = wrapperScriptException; } else { wrapperException = new WrapperException(message, EngineName, EngineVersion, originalException); } wrapperException.Description = description; return(wrapperException); }