예제 #1
0
        public async Task <JObject> GetMarkdownIt(string text)
        {
            _jsengine = _jsengine ?? JsEngineSwitcher.Instance.CreateDefaultEngine();

            var version = "8.4.0";

            if (_mardownit == null)
            {
                _mardownit = await _httpClient.GetStringAsync($"https://raw.githubusercontent.com/markdown-it/markdown-it/{version}/dist/markdown-it.min.js");

                _jsengine.Execute(_mardownit);
                _jsengine.Evaluate("var MarkdownIt = markdownit();");
            }

            var inputval = "input_" + Guid.NewGuid().ToString().Replace("-", "_");

            _jsengine.SetVariableValue(inputval, text);

            var script = $"MarkdownIt.render({inputval});";
            var result = _jsengine.Evaluate(script)?.ToString();

            _jsengine.RemoveVariable(inputval);

            var jsonResult = new JObject
            {
                ["name"]    = "markdown-it",
                ["version"] = version,
                ["html"]    = result
            };

            return(jsonResult);
        }
예제 #2
0
        public void Initialize()
        {
            _jsEngine = _jsEngineFactory.CreateEngine();

            // Execute each bundle
            foreach (var reactBundleFile in ReactServerSideBundle.BundleFiles)
            {
                // Fix console is undefined errors
                _jsEngine.Evaluate("if (typeof console === 'undefined') console = { log: function() {}, error: function() {} };");

                if (reactBundleFile.ToLowerInvariant().StartsWith("http"))
                {
                    var contents = new HttpClient().GetStringAsync(reactBundleFile).Result;

                    _jsEngine.Evaluate(contents);

                    //var newCode = _jsEngine.Precompile(contents);
                    //_jsEngine.Execute(newCode);
                }
                else
                {
                    _jsEngine.ExecuteFile(_mapServerPath.MapServerPath(reactBundleFile), null);
                }
            }
        }
예제 #3
0
        public ProcessHostedWithChakraCore(string javascriptPreparedToRun)
        {
            javascriptEngine = new ChakraCoreJsEngine(
                new ChakraCoreSettings
            {
                DisableEval = true,
                EnableExperimentalFeatures = true
            }
                );

            var initAppResult = javascriptEngine.Evaluate(javascriptPreparedToRun);

            var resetAppStateResult = javascriptEngine.Evaluate(
                ProcessFromElm019Code.appStateJsVarName + " = " + ProcessFromElm019Code.initStateJsFunctionPublishedSymbol + ";");
        }
예제 #4
0
        /// <summary>
        /// "Optimizes" a CSS code by using Sergey Kryzhanovsky's CSSO
        /// </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 Optimize(string content, string path)
        {
            Initialize();

            string newContent;

            try
            {
                var result = _jsEngine.Evaluate <string>(
                    string.Format(OPTIMIZATION_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 CssOptimizationException(FormatErrorDetails(errors[0], content, path));
                }

                newContent = json.Value <string>("minifiedCode");
            }
            catch (JsRuntimeException e)
            {
                throw new CssOptimizationException(JsErrorHelpers.Format(e));
            }

            return(newContent);
        }
예제 #5
0
        public async Task <JObject> GetCommonMarkJs(string text)
        {
            _jsengine = _jsengine ?? JsEngineSwitcher.Instance.CreateDefaultEngine();

            var version = "0.28.1";

            if (_commonmarkjs == null)
            {
                _commonmarkjs = await _httpClient.GetStringAsync($"https://raw.githubusercontent.com/commonmark/commonmark.js/{version}/dist/commonmark.min.js");

                _jsengine.Execute(_commonmarkjs);
            }

            var inputval = "input_" + Guid.NewGuid().ToString().Replace("-", "_");

            _jsengine.SetVariableValue(inputval, text);

            var script = $"(new commonmark.HtmlRenderer()).render((new commonmark.Parser()).parse({inputval}));";
            var result = _jsengine.Evaluate(script)?.ToString();

            _jsengine.RemoveVariable(inputval);

            var jsonResult = new JObject
            {
                ["name"]    = "commonmark.js",
                ["version"] = version,
                ["html"]    = result
            };

            return(jsonResult);
        }
예제 #6
0
        /// <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 (JsRuntimeException e)
            {
                throw new CssAutoprefixingException(JsErrorHelpers.Format(e));
            }

            return(autoprefixingResult);
        }
예제 #7
0
        /// <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 (JsRuntimeException e)
            {
                throw new HandlebarsCompilationException(JsErrorHelpers.Format(e));
            }

            return(newContent);
        }
예제 #8
0
        /// <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 (JsRuntimeException e)
            {
                throw new CoffeeScriptCompilationException(JsErrorHelpers.Format(e));
            }

            return(newContent);
        }
예제 #9
0
        public string Compile(string content, string path, BabelJsCompilationOptions options = null)
        {
            string newContent;
            var    currentOptionsString = ConvertCompilationOptionsToJson(options ?? _defaultOptions, path).ToString(Formatting.None);

            lock (_compilationSynchronizer)
            {
                Initialize();

                try
                {
                    var result = _jsEngine.Evaluate <string>(
                        string.Format(COMPILATION_FUNCTION_CALL_TEMPLATE,
                                      JsonConvert.SerializeObject(content),
                                      currentOptionsString));
                    var json = JObject.Parse(result);

                    var errors = json["errors"] as JArray;
                    if (errors != null && errors.Count > 0)
                    {
                        throw new BabelJsCompilerException(FormatErrorDetails(errors[0], content, path));
                    }

                    newContent = json.Value <string>("compiledCode");
                }
                catch (JsRuntimeException e)
                {
                    throw new Exception(JsRuntimeErrorHelpers.Format(e));
                }
            }

            return(newContent);
        }
        /// <summary>
        /// Ensures that Babel has been loaded into the JavaScript engine.
        /// </summary>
        private void EnsureBabelLoaded(IJsEngine engine)
        {
            // If Babel is disabled in the config, don't even try loading it
            if (!_config.LoadBabel)
            {
                throw new BabelNotLoadedException();
            }

            var babelLoaded = engine.Evaluate <bool>("typeof ReactNET_transform !== 'undefined'");

            if (!babelLoaded)
            {
#if NET40
                var assembly = typeof(ReactEnvironment).Assembly;
#else
                var assembly = typeof(ReactEnvironment).GetTypeInfo().Assembly;
#endif
                const string resourceName = "React.Core.Resources.babel.generated.min.js";

                if (_config.AllowJavaScriptPrecompilation &&
                    engine.TryExecuteResourceWithPrecompilation(_cache, resourceName, assembly))
                {
                    // Do nothing.
                }
                else
                {
                    engine.ExecuteResource(resourceName, assembly);
                }
            }
        }
예제 #11
0
        public static string GetCondition(List <string> constants, List <int> useConstants, string condition, string className)
        {
            GetJsEngineSwitcher();
            return(antiDupCache.GetOrAdd(condition, () =>
            {
                var js = @"var antlr4={};
antlr4.Token={};
antlr4.Token.EOF=-1;
var {3}={};
{3}.EOF = antlr4.Token.EOF;
{0}
var testNums=[{1}];
var result=[];
for(var i=0;i<testNums.length;i++){
    var _la=testNums[i];
    if({2}){
        result.push(_la)
    }
}
outResult=result.join(',');
";
                js = js.Replace("{0}", string.Join("\r\n", constants));
                js = js.Replace("{1}", string.Join(",", useConstants));
                js = js.Replace("{2}", condition);
                js = js.Replace("{3}", className);

                IJsEngine engine = JsEngineSwitcher.Current.CreateEngine(JintJsEngine.EngineName);
                engine.SetVariableValue("outResult", "");
                engine.Evaluate(js);
                var result = engine.GetVariableValue <string>("outResult");
                engine.Dispose();
                return result;
            }));
        }
예제 #12
0
        public override IRow Operate(IRow row)
        {
            foreach (var field in _input)
            {
                _engine.SetVariableValue(field.Alias, row[field]);
            }
            try {
                var value = Context.Field.Convert(_engine.Evaluate(Context.Operation.Script));
                if (value == null && !_errors.ContainsKey(0))
                {
                    Context.Error($"{_engine.Name} transform in {Context.Field.Alias} returns null!");
                    _errors[0] = $"{_engine.Name} transform in {Context.Field.Alias} returns null!";
                }
                else
                {
                    row[Context.Field] = value;
                }
            } catch (JsRuntimeException jse) {
                if (!_errors.ContainsKey(jse.LineNumber))
                {
                    Context.Error("Script: " + Context.Operation.Script.Replace("{", "{{").Replace("}", "}}"));
                    Context.Error(jse, "Error Message: " + jse.Message);
                    Context.Error("Variables:");
                    foreach (var field in _input)
                    {
                        Context.Error($"{field.Alias}:{row[field]}");
                    }
                    _errors[jse.LineNumber] = jse.Message;
                }
            }


            return(row);
        }
예제 #13
0
        /// <summary>
        /// Ensures that Babel has been loaded into the JavaScript engine.
        /// </summary>
        private void EnsureBabelLoaded(IJsEngine engine)
        {
            // If Babel is disabled in the config, don't even try loading it
            if (!_config.LoadBabel)
            {
                throw new BabelNotLoadedException();
            }

            var babelLoaded = engine.Evaluate <bool>("typeof ReactNET_transform !== 'undefined'");

            if (!babelLoaded)
            {
#if NET40
                var assembly = typeof(ReactEnvironment).Assembly;
#else
                var assembly = typeof(ReactEnvironment).GetTypeInfo().Assembly;
#endif
                string resourceName = _config.BabelVersion == BabelVersions.Babel7 || _config.BabelVersion == null
                                        ? "React.Core.Resources.babel.generated.min.js"
                                        : _config.BabelVersion == BabelVersions.Babel6
                                                ? "React.Core.Resources.babel-legacy.generated.min.js"
                                                : throw new ReactConfigurationException("BabelVersion was not null, but did not contain a valid value.");

                if (_config.AllowJavaScriptPrecompilation &&
                    engine.TryExecuteResourceWithPrecompilation(_cache, resourceName, assembly))
                {
                    // Do nothing.
                }
                else
                {
                    engine.ExecuteResource(resourceName, assembly);
                }
            }
        }
        /// <summary>
        /// Performs a sanity check to ensure the specified engine type is usable.
        /// </summary>
        /// <param name="engine">Engine to test</param>
        /// <param name="allowMsie">Whether the MSIE engine can be used</param>
        /// <returns></returns>
        private static bool EngineIsUsable(IJsEngine engine, bool allowMsie)
        {
            var isUsable = engine.Evaluate <int>("1 + 1") == 2;
            var isMsie   = engine is MsieJsEngine;

            return(isUsable && (!isMsie || allowMsie));
        }
예제 #15
0
        /// <summary>
        /// Performs a sanity check to ensure the specified engine type is usable.
        /// </summary>
        /// <param name="engine">Engine to test</param>
        /// <param name="allowMsie">Whether the MSIE engine can be used</param>
        /// <returns></returns>
        private static bool EngineIsUsable(IJsEngine engine, bool allowMsie)
        {
            // Perform a sanity test to ensure this engine is usable
            var isUsable = engine.Evaluate <int>("1 + 1") == 2;
            var isMsie   = engine is MsieJsEngine;

            return(isUsable && (!isMsie || allowMsie));
        }
예제 #16
0
        private CompilationResult InnerCompile(string content, bool indentedSyntax, string inputPath,
                                               string outputPath, string sourceMapPath, CompilationOptions options)
        {
            InitializeCompiler();

            string inputFilePath     = inputPath;
            string outputFilePath    = outputPath;
            string sourceMapFilePath = sourceMapPath;

            ProcessFilePaths(ref inputFilePath, ref outputFilePath, ref sourceMapFilePath);

            string serializedContent        = _jsonSerializer.SerializePrimitiveType(content);
            string serializedIndentedSyntax = _jsonSerializer.SerializePrimitiveType(indentedSyntax);
            string serializedInputPath      = _jsonSerializer.SerializePrimitiveType(inputFilePath);
            string serializedOutputPath     = _jsonSerializer.SerializePrimitiveType(outputFilePath);
            string serializedSourceMapPath  = _jsonSerializer.SerializePrimitiveType(sourceMapFilePath);
            string serializedOptions        = options != null?_jsonSerializer.SerializeObject(options) : "null";

            CompilationResult compilationResult = null;

            try
            {
                string serializedResult = _jsEngine.Evaluate <string>($"sassHelper.compile({serializedContent}, " +
                                                                      $"{serializedIndentedSyntax}, {serializedInputPath}, {serializedOutputPath}, " +
                                                                      $"{serializedSourceMapPath}, {serializedOptions});");

                compilationResult = _jsonSerializer.DeserializeObject <CompilationResult>(serializedResult);
            }
            catch (SassCompilationException)
            {
                throw;
            }
            catch (JsException e)
            {
                throw new SassCompilationException(
                          string.Format(Strings.Compiler_JsErrorDuringCompilation, e.Message), e)
                      {
                          Description = e.Message,
                          File        = inputPath ?? string.Empty
                      };
            }

            return(compilationResult);
        }
예제 #17
0
        public string Transform(string markdown)
        {
            _jsEngine.Evaluate(@"marked.setOptions({
  highlight: function (code) {
    return hljs.highlightAuto(code).value;
  }
});"
                               );

            return(_jsEngine.CallFunction <string>("marked", markdown));
        }
        /// <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);
        }
예제 #19
0
        public async Task <ComicPage[]> GetPagesAsync(string targetUrl)
        {
            var    blocks = new List <ComicPage>();
            string str    = null;

            using (var sr = new StreamReader(await CreateRequest(targetUrl)))
            {
                str = sr.ReadToEnd();
            }
            var match = regex.Match(str);
            var sc    = match.Groups[0].Value + ";pages;";
            var strx  = v8.Evaluate(sc)?.ToString();

            if (strx is null)
            {
#if NETSTANDARD1_3 || NET452
                return(new ComicPage[0]);
#else
                return(Array.Empty <ComicPage>());
#endif
            }
            string[] inn     = null;
            var      visitor = JsonVisitor.FromString(strx.Replace("\r\n", "$@$"));
            try
            {
                if (strx.StartsWith("{"))
                {
                    inn = visitor["page_url"].ToString().Split(new[] { "$@$" }, StringSplitOptions.RemoveEmptyEntries);
                }
                else
                {
                    inn = visitor.ToEnumerable().Select(x => x.ToString()).ToArray();
                }
                foreach (var item in inn)
                {
                    var val  = item.ToString().Trim();
                    var name = HttpUtility.UrlDecode(val.Split('/').Last());
                    blocks.Add(new ComicPage
                    {
                        Name      = name,
                        TargetUrl = "https://images.dmzj.com/" + val
                    });
                }
            }
            finally
            {
                visitor.Dispose();
            }
            return(blocks.ToArray());
        }
        /// <summary>
        /// Gets a factory for the most appropriate JavaScript engine for the current environment.
        /// The first functioning JavaScript engine with the lowest priority will be used.
        /// </summary>
        /// <returns>Function to create JavaScript engine</returns>
        private static Func <IJsEngine> GetFactory(IEnumerable <Registration> availableFactories)
        {
            var availableEngineFactories = availableFactories
                                           .OrderBy(x => x.Priority)
                                           .Select(x => x.Factory);

            foreach (var engineFactory in availableEngineFactories)
            {
                IJsEngine engine = null;
                try
                {
                    engine = engineFactory();
                    // Perform a sanity test to ensure this engine is usable
                    if (engine.Evaluate <int>("1 + 1") == 2)
                    {
                        // Success! Use this one.
                        return(engineFactory);
                    }
                }
                catch (Exception ex)
                {
                    // This engine threw an exception, try the next one
                    Trace.WriteLine(string.Format("Error initialising {0}: {1}", engineFactory, ex));
                }
                finally
                {
                    if (engine != null)
                    {
                        engine.Dispose();
                    }
                }
            }

            // Epic fail, none of the engines worked. Nothing we can do now.
            // Throw an error relevant to the engine they should be able to use.
            if (JavaScriptEngineUtils.EnvironmentSupportsClearScript())
            {
                JavaScriptEngineUtils.EnsureEngineFunctional <V8JsEngine, ClearScriptV8InitialisationException>(
                    ex => new ClearScriptV8InitialisationException(ex.Message)
                    );
            }
            else if (JavaScriptEngineUtils.EnvironmentSupportsVroomJs())
            {
                JavaScriptEngineUtils.EnsureEngineFunctional <VroomJsEngine, VroomJsInitialisationException>(
                    ex => new VroomJsInitialisationException(ex.Message)
                    );
            }
            throw new ReactEngineNotFoundException();
        }
예제 #21
0
        /// <summary>
        /// Ensures that Babel has been loaded into the JavaScript engine.
        /// </summary>
        private void EnsureBabelLoaded(IJsEngine engine)
        {
            // If Babel is disabled in the config, don't even try loading it
            if (!_config.LoadBabel)
            {
                throw new BabelNotLoadedException();
            }

            var babelLoaded = engine.Evaluate <bool>("typeof global.Babel !== 'undefined'");

            if (!babelLoaded)
            {
                engine.ExecuteResource("React.node_modules.babel_core.browser.js", typeof(ReactEnvironment).Assembly);
            }
        }
예제 #22
0
        public string Transform(string markdown)
        {
            string result;

            lock (_compilationSynchronizer)
            {
                Initialize();

                _jsEngine.SetVariableValue("_markdownString", markdown);

                result = _jsEngine.Evaluate <string>("markedHelper.compile(_markdownString)");
            }

            return(HtmlUtility.SanitizeHtml(result));
        }
예제 #23
0
        /// <summary>
        /// Ensures that Babel has been loaded into the JavaScript engine.
        /// </summary>
        private void EnsureBabelLoaded(IJsEngine engine)
        {
            // If Babel is disabled in the config, don't even try loading it
            if (!_config.LoadBabel)
            {
                throw new BabelNotLoadedException();
            }

            var babelLoaded = engine.Evaluate <bool>("typeof ReactNET_transform !== 'undefined'");

            if (!babelLoaded)
            {
                engine.ExecuteResource("React.Resources.babel.generated.min.js", typeof(ReactEnvironment).Assembly);
            }
        }
예제 #24
0
        /// <summary>
        /// Initializes a Sass compiler
        /// </summary>
        private void InitializeCompiler()
        {
            if (_initialized)
            {
                return;
            }

            lock (_initializationSynchronizer)
            {
                if (_initialized)
                {
                    return;
                }

                string serializedOptions = _jsonSerializer.SerializeObject(_options);

                try
                {
                    _jsEngine = _createJsEngineInstance();
                    _jsEngine.EmbedHostObject(FILE_MANAGER_VARIABLE_NAME, _fileManager);
                    _jsEngine.SetVariableValue(CURRENT_OS_PLATFORM_NAME, GetCurrentOSPlatformName());

                    Assembly assembly = this.GetType()
#if !NET40
                                        .GetTypeInfo()
#endif
                                        .Assembly
                    ;

                    _jsEngine.ExecuteResource(ResourceHelpers.GetResourceName(ES6_POLYFILLS_FILE_NAME), assembly, true);
                    _jsEngine.ExecuteResource(ResourceHelpers.GetResourceName(SASS_LIBRARY_FILE_NAME), assembly, true);
                    _jsEngine.ExecuteResource(ResourceHelpers.GetResourceName(SASS_HELPER_FILE_NAME), assembly, true);
                    _jsEngine.Execute($"var sassHelper = new SassHelper({serializedOptions});");

                    _version = _jsEngine.Evaluate <string>("SassHelper.getVersion();");
                }
                catch (JsEngineLoadException e)
                {
                    throw SassErrorHelpers.WrapCompilerLoadException(e);
                }
                catch (JsException e)
                {
                    throw SassErrorHelpers.WrapCompilerLoadException(e, true);
                }

                _initialized = true;
            }
        }
예제 #25
0
        /// <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);
        }
예제 #26
0
        public async Task <ComicPage[]> GetPagesAsync(string targetUrl)
        {
            var str = string.Empty;

            using (var sr = new StreamReader(await GetStreamAsync(targetUrl)))
            {
                str = sr.ReadToEnd();
            }
            var html = new HtmlDocument();

            html.LoadHtml(str);
            var eval = await GetJsEvalAsync(FetchJsEvalAsync);

            var dataBlock  = dataRegex.Match(str);
            var noticLeft  = str.IndexOf("window[\"n", str.IndexOf("window[\"n") + 4);
            var noticRight = str.IndexOf(";", noticLeft);
            var notic      = str.Substring(noticLeft, noticRight - noticLeft);
            var data       = dataBlock.Groups[1].Value;
            var dataJs     = "var DATA='" + data + "';window.DATA=DATA;";
            var sb         = new StringBuilder();

            sb.Append(varJs);
            sb.Append(dataJs);
            sb.Append(notic + ";");
            sb.Append(eval);
            sb.Append(";JSON.stringify(_v);");
            var val = jsEngine.Evaluate(sb.ToString()).ToString();

            using (var doc = JsonVisitor.FromString(val))
            {
                var pages = new List <ComicPage>();
                var pics  = doc["picture"].ToEnumerable();
                foreach (var item in pics)
                {
                    var pid  = item["pid"];
                    var url  = item["url"];
                    var page = new ComicPage
                    {
                        Name      = pid.ToString(),
                        TargetUrl = url.ToString()
                    };
                    pages.Add(page);
                }
                return(pages.ToArray());
            }
        }
예제 #27
0
        /// <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);
        }
예제 #28
0
        /// <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);
        }
예제 #29
0
        public override object Evaluate(string script, params KeyValuePair <string, object>[] kvp)
        {
            object result = null;

            if (kvp != null)
            {
                foreach (var obj in kvp)
                {
                    //判定是否为值类型
                    if (obj.Value.GetType().IsValueType || obj.Value is string)
                    {
                        js.SetVariableValue(obj.Key, obj.Value);
                    }
                    else
                    {
                        js.EmbedHostObject(obj.Key, obj.Value);
                    }
                }
            }
            try
            {
                result = js.Evaluate(script);
            }
            catch (JavaScriptEngineSwitcher.Core.JsException jse)
            {
                if (jse.InnerException != null)
                {
                    if (jse.InnerException is VroomJs.JsException)
                    {
                        var vjse = (VroomJs.JsException)jse.InnerException;
                        throw new HostJsException(jse.Message, script, vjse.Line, vjse.Column);
                    }
                }
                else
                {
                    throw new HostJsException(jse.Message, script, 0, 0);
                }
            }

            return(result);
        }
        /// <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);
        }
예제 #31
0
		/// <summary>
		/// Performs a sanity check to ensure the specified engine type is usable.
		/// </summary>
		/// <param name="engine">Engine to test</param>
		/// <param name="allowMsie">Whether the MSIE engine can be used</param>
		/// <returns></returns>
		private static bool EngineIsUsable(IJsEngine engine, bool allowMsie)
		{
			// Perform a sanity test to ensure this engine is usable
			var isUsable = engine.Evaluate<int>("1 + 1") == 2;
			var isMsie = engine is MsieJsEngine;
			return isUsable && (!isMsie || allowMsie);
		}
		/// <summary>
		/// Performs a sanity check to ensure the specified engine type is usable.
		/// </summary>
		/// <param name="engine">Engine to test</param>
		/// <param name="allowMsie">Whether the MSIE engine can be used</param>
		/// <returns></returns>
		private static bool EngineIsUsable(IJsEngine engine, bool allowMsie)
		{
			// Perform a sanity test to ensure this engine is usable
			var isUsable = engine.Evaluate<int>("1 + 1") == 2;
#if NETSTANDARD16
            var isMsie = false;
#else
            var isMsie = engine is MsieJsEngine;
#endif
			return isUsable && (!isMsie || allowMsie);
		}