public string Minify(string content, bool enableOptimizations = false, bool obfuscate = false, CultureInfo culture = null)
 {
     JavaScriptCompressor javaScriptCompressor = new JavaScriptCompressor();
     javaScriptCompressor.CompressionType = CompressionType.Standard;
     javaScriptCompressor.ThreadCulture = culture ?? CultureInfo.InvariantCulture;
     javaScriptCompressor.Encoding = Encoding.UTF8;
     javaScriptCompressor.DisableOptimizations = !enableOptimizations;
     javaScriptCompressor.IgnoreEval = true;
     javaScriptCompressor.LineBreakPosition = -1;
     javaScriptCompressor.ObfuscateJavascript = obfuscate;
     javaScriptCompressor.PreserveAllSemicolons = false;
     return javaScriptCompressor.Compress(content);
 }
Esempio n. 2
0
        public ScriptBuilder(NgTemplateCacheBuilder cacheBuilder, JavaScriptCompressor compressor, CompressorReporter reporter)
        {
            this.cacheBuilder = cacheBuilder;

            compressor.ErrorReporter = reporter;
            this.compressor = compressor;
        }
        public static string GetScript(ScriptIds ids, string token)
        {
            var script = @"(function (v, t) {
                if (!t) t = 'hidden';
                var chk = function () {
                    var elem = document.getElementById('" + ids.ScriptId + @"');
                    document.getElementById('" + ids.HoneyPotContainerId + @"').style.display = 'none';
                    if (elem) {
                        var newElem = document.createElement('div');
                        newElem.innerHTML = '<input type=""' + t + '"" name=""" + ids.TokenId + @""" value=""' + v + '"" />';
                        elem.parentNode.appendChild(newElem);
                        elem.parentNode.removeChild(elem);
                    } else {
                        window.setTimeout(chk, 500);
                    }
                };
                window.setTimeout(chk, 500);
                document.getElementById('" + ids.HoneyPotContainerId + @"').style.display = 'none';
                }('" + token + @"'));";

            var compressor = new JavaScriptCompressor
            {
                Encoding = Encoding.UTF8,
                DisableOptimizations = false,
                ObfuscateJavascript = true,
                PreserveAllSemicolons = true,
                IgnoreEval = true,
                ThreadCulture = Globalization.CultureInfo.InvariantCulture
            };

            var example = compressor.Compress(script);

            return example;
        }
Esempio n. 4
0
 public override void Process(BundleContext context, BundleResponse response)
 {
     var compressor = new JavaScriptCompressor();
     
     response.Content = compressor.Compress(response.Content);
     response.ContentType = ContentTypes.JavaScript;
 }
Esempio n. 5
0
 protected override void Minify(string fileName, string outputFileName)
 {
     Log(Level.Info, "Minifying JavaScript {0} -> {1}", fileName, outputFileName);
     var compressor = new JavaScriptCompressor(File.ReadAllText(fileName));
     string output = compressor.Compress();
     File.WriteAllText(outputFileName, output);
 }
        public override bool Execute()
        {
            var files = new List<string>();
            if (RequireConfigs != null)
            {
                files = RequireConfigs.Select(r => r.GetMetadata("FullPath")).ToList();    
            }

            var entryPointOveride = string.Empty;

            if (EntryPointOverride != null)
            {
                entryPointOveride = EntryPointOverride.GetMetadata("FullPath");
            }

            this.configProcessor = ConfigProcessorFactory.Create(AutoCompressor, ProjectPath, PackagePath, entryPointOveride, files, FileHelpers.ParseEncoding(EncodingType));

            var bundles = new List<Bundle>();
            try
            {
                bundles = this.configProcessor.ParseConfigs();
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex);
                return false;
            }

            if (bundles.Any())
            {
                EnsureOutputDirectoriesExist(bundles);
                var compressor = new JavaScriptCompressor
                                     {
                                         Encoding = FileHelpers.ParseEncoding(EncodingType)
                                     };
                foreach (var bundle in bundles)
                {
                    if (!bundle.Files.Any())
                    {
                        continue;
                    }

                    var taskEngine = new CompressorTaskEngine(new MsBuildLogAdapter(Log), compressor)
                    {
                        CompressionType = CompressionType,
                        DeleteSourceFiles = false,
                        EncodingType = EncodingType,
                        LineBreakPosition = -1,
                        LoggingType = LoggingType,
                        OutputFile = bundle.Output,
                        SourceFiles = bundle.Files.ToArray()
                    };
             

                    taskEngine.Execute();
                }
            }
            
            return true;
        }
        public void Process(BundleContext context, BundleResponse response)
        {
            var compiler = new HandlebarsCompiler();
            var templates = new Dictionary<string, string>();
            var server = context.HttpContext.Server;

            foreach (var bundleFile in response.Files)
            {
                var filePath = server.MapPath(bundleFile.VirtualFile.VirtualPath);
                var bundleRelativePath = GetRelativePath(server, bundleFile, filePath);
                var templateName = namer.GenerateName(bundleRelativePath, bundleFile.VirtualFile.Name);
                var template = File.ReadAllText(filePath);
                var compiled = compiler.Precompile(template, false);

                templates[templateName] = compiled;
            }
            StringBuilder javascript = new StringBuilder();
            foreach (var templateName in templates.Keys)
            {
                javascript.AppendFormat("Ember.TEMPLATES['{0}']=", templateName);
                javascript.AppendFormat("Ember.Handlebars.template({0});", templates[templateName]);
            }

            var Compressor = new JavaScriptCompressor();
            var compressed = Compressor.Compress(javascript.ToString());

            response.ContentType = "text/javascript";
            response.Cacheability = HttpCacheability.Public;
            response.Content = compressed;
        }
Esempio n. 8
0
        public static string Minify(string fullFileName, string text, EnvDTE.ProjectItem projectItem,Yui.JsSettings jsSettings)
        {
            string returnScript = string.Empty;
            var reporter = new EcmaScriptErrorReporter(fullFileName, projectItem);
            try
            {
                // http://chirpy.codeplex.com/workitem/133
                int lineBreakPosition = jsSettings.LineBreakPosition;
                if (lineBreakPosition == 0)
                {
                    lineBreakPosition = -1;
                }

                // http://chirpy.codeplex.com/workitem/54
                // http://chirpy.codeplex.com/workitem/60
                var compressor = new JavaScriptCompressor(text, true, System.Text.Encoding.UTF8, System.Globalization.CultureInfo.InvariantCulture, false, reporter);
                returnScript = compressor.Compress(jsSettings.IsObfuscateJavascript, jsSettings.PreserveAllSemiColons, jsSettings.DisableOptimizations, lineBreakPosition);
            }
            catch (System.Exception eError)
            {
                returnScript= string.Format("/* error = {0} */",eError.Message);
            }

            return returnScript;
        }
Esempio n. 9
0
        public ResourceCompressor(CssCompressor cssCompressor, JavaScriptCompressor jsCompressor)
        {
            Ensure.That(() => cssCompressor).IsNotNull();
            Ensure.That(() => jsCompressor).IsNotNull();

            this.cssCompressor = cssCompressor;
            this.jsCompressor = jsCompressor;
        }
Esempio n. 10
0
 static string jsMinify(IEnumerable<string> files) {
   StringBuilder sb = new StringBuilder(); 
   var compr = new JavaScriptCompressor();
   foreach (var fn in files) {
     var file = File.ReadAllText(fn, Encoding.UTF8);
     var res = compr.Compress(file);
     sb.Append(res); 
   }
   return sb.ToString();
 }
Esempio n. 11
0
 public YuiMinifier(LoggingType loggingType, bool obfuscateJavaScript, bool preserveAllSemicolons, bool disableOptimizations, bool ignoreEval)
 {
     compressor = new JavaScriptCompressor
                      {
                          LoggingType = loggingType,
                          ObfuscateJavascript = obfuscateJavaScript,
                          PreserveAllSemicolons = preserveAllSemicolons,
                          DisableOptimizations = disableOptimizations,
                          IgnoreEval = ignoreEval
                      };
 }
 public HandlebarsCompiler()
 {
     Engine = new Jurassic.ScriptEngine();
     var ass = typeof(HandlebarsCompiler).Assembly;
     Engine.Execute("var exports = {};");
     Engine.Execute("var module = {};");
     Engine.Execute(GetEmbeddedResource("HandlebarsHelper.Scripts.handlebars-v2.0.0.js", ass));
     Engine.Execute(GetEmbeddedResource("HandlebarsHelper.Scripts.ember-template-compiler.js", ass));
     Engine.Execute("var precompile = exports.precompile;");
     Compressor = new JavaScriptCompressor();
 }
Esempio n. 13
0
 public override void Parse(TextReader reader, IProcessorContext context)
 {
     if (AssetPipeline.MinifyJs)
     {
         var compressor = new JavaScriptCompressor(reader.ReadToEnd());
         context.Output.Write(compressor.Compress());
     }
     else
     {
         context.Output.Write(reader.ReadToEnd());
     }
 }
Esempio n. 14
0
        public override void Process(BundleContext context, BundleResponse response)
        {
            response.ContentType = ContentTypes.JavaScript;

            if (context.HttpContext.IsDebuggingEnabled)
            {
                return;
            }

            var compressor = new JavaScriptCompressor();
            response.Content = compressor.Compress(response.Content);
        }
Esempio n. 15
0
 /// <inheritdoc cref="IResourceMinifier.Minify" />
 public string Minify(Settings settings, ResourceSet resourceSet, string combinedContent)
 {
     var compressor = new JavaScriptCompressor();
     compressor.Encoding = Encoding.UTF8;
     compressor.ThreadCulture = CultureInfo.InvariantCulture;
     compressor.LoggingType = IsVerboseLogging == true ? LoggingType.Debug : LoggingType.None;
     compressor.PreserveAllSemicolons = PreserveAllSemicolons == null ? false : PreserveAllSemicolons.Value;
     compressor.DisableOptimizations = DisableOptimizations == null ? false : DisableOptimizations.Value;
     compressor.LineBreakPosition = LineBreakPosition == null ? -1 : LineBreakPosition.Value;
     compressor.IgnoreEval = IgnoreEval == null ? true : IgnoreEval.Value;
     compressor.ObfuscateJavascript = ObfuscateJavascript == null ? true : ObfuscateJavascript.Value;
     return compressor.Compress(combinedContent);
 }
Esempio n. 16
0
 public ResourceCompressor(CssCompressor cssCompressor, JavaScriptCompressor jsCompressor)
 {
     if (cssCompressor == null)
     {
         throw new ArgumentNullException("cssCompressor");
     }
     if (jsCompressor == null)
     {
         throw new ArgumentNullException("jsCompressor");
     }
     this.cssCompressor = cssCompressor;
     this.jsCompressor = jsCompressor;
 }
Esempio n. 17
0
 public string Process(string includedVirtualPath, string input)
 {
     if (BundleTable.EnableOptimizations)
     {
         var compressor = new JavaScriptCompressor
         {
             CompressionType = CompressionType.Standard,
             Encoding = Encoding.UTF8,
             ObfuscateJavascript = obfuscate,
         };
         input = compressor.Compress(input);
     }
     return input;
 }
Esempio n. 18
0
 public CompileResults Compile(string inPath, string outPath)
 {
     using (StreamReader sr = new StreamReader(inPath))
     {
         string content = sr.ReadToEnd();
         JavaScriptCompressor x = new JavaScriptCompressor();
         string output = x.Compress(content);
         using (StreamWriter sw = new StreamWriter(outPath))
         {
             sw.Write(output);
         }
     }
     return null;
 }
Esempio n. 19
0
 public YuiMinifier(LoggingType loggingType, bool obfuscateJavaScript, bool preserveAllSemicolons, bool disableOptimizations, bool ignoreEval, int lineBreakPosition, Encoding encoding, CultureInfo cultureInfo)
 {
     compressor = new JavaScriptCompressor
                      {
                          LoggingType = loggingType,
                          ObfuscateJavascript = obfuscateJavaScript,
                          PreserveAllSemicolons = preserveAllSemicolons,
                          DisableOptimizations = disableOptimizations,
                          LineBreakPosition = lineBreakPosition,
                          Encoding = encoding,
                          ThreadCulture = cultureInfo,
                          IgnoreEval = ignoreEval
                      };
 }
Esempio n. 20
0
 private static string CompressJS(string content)
 {
     string results = "";
     try
     {
         var jsCompressor = new JavaScriptCompressor();
         results = jsCompressor.Compress(content);
     }
     catch (Exception ex)
     {
         WriteLog(ex);
     }
     return results;
 }
Esempio n. 21
0
 public string Process(string includedVirtualPath, string input)
 {
     if (BundleTable.EnableOptimizations)
     {
         var compressor = new JavaScriptCompressor
         {
             Encoding = Encoding.UTF8,
             ObfuscateJavascript = obfuscate,
             PreserveAllSemicolons = true,
         };
         input = compressor.Compress(input);
     }
     return input;
 }
 protected override byte[] GenerateCode(string inputFileContent)
 {
     string output = string.Empty;
     try
     {
         var JsCompressor = new JavaScriptCompressor();
         output = JsCompressor.Compress(inputFileContent);
     }
     catch (Exception e)
     {
         throw new COMException(string.Format("{0}: {1}\n{2}",
                 e.GetType().Name, e.Message, e.StackTrace));
     }
     return Encoding.ASCII.GetBytes(output);
 }
        /// <summary>
        /// Constructs a instance of YUI JS-minifier
        /// </summary>
        /// <param name="yuiConfig">Configuration settings of YUI Minifier</param>
        public YuiJsMinifier(YuiSettings yuiConfig)
        {
            _jsCompressor = new JavaScriptCompressor();

            JsMinifierSettings jsMinifierConfig = yuiConfig.JsMinifier;
            CompressionType = jsMinifierConfig.CompressionType;
            ObfuscateJavascript = jsMinifierConfig.ObfuscateJavascript;
            PreserveAllSemicolons = jsMinifierConfig.PreserveAllSemicolons;
            DisableOptimizations = jsMinifierConfig.DisableOptimizations;
            IgnoreEval = jsMinifierConfig.IgnoreEval;
            LineBreakPosition = jsMinifierConfig.LineBreakPosition;
            Encoding = ParseEncoding(jsMinifierConfig.Encoding);
            ThreadCulture = ParseThreadCulture(jsMinifierConfig.ThreadCulture);
            Severity = jsMinifierConfig.Severity;
        }
Esempio n. 24
0
        /// <summary>
        /// Process the request
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            DateTime mod = new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime ;
            var compressor = new JavaScriptCompressor() ;

            if (!ClientCache.HandleClientCache(context, resource, mod)) {
                StreamReader io = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)) ;
                context.Response.ContentType = "text/javascript" ;
            #if DEBUG
                context.Response.Write(io.ReadToEnd()) ;
            #else
                context.Response.Write(compressor.Compress(io.ReadToEnd())) ;
            #endif
                io.Close() ;
            }
        }
Esempio n. 25
0
        public static MvcHtmlString MinifyInlineScript(this HtmlHelper html, Func <object, object> markup)
        {
            string notMinifiedJs = (markup.Invoke(html.ViewContext)?.ToString() ?? "").TrimStart("<script>")
                                   .TrimStart("<text>").TrimEnd("</script>").TrimEnd("</text>");

            var minifier = new Yahoo.Yui.Compressor.JavaScriptCompressor()
            {
                CompressionType       = CompressionType.Standard,
                Encoding              = Encoding.UTF8,
                ObfuscateJavascript   = true,
                PreserveAllSemicolons = true,
            };
            var minifiedJs = minifier.Compress(notMinifiedJs);

            return(new MvcHtmlString("<script type='text/javascript'>" + minifiedJs + "</script>"));
        }
		public YuiJavaScriptTransformer(
			CompressionType compressionType = CompressionType.Standard,
			bool enableOptimizations = true,
			bool ignoreEval = false,
			int lineBreakPosition = -1,
			bool obfuscateJavaScript = true,
			bool preserveAllSemiColons = false)
		{
			_compressor = new JavaScriptCompressor
				{
					CompressionType = compressionType,
					DisableOptimizations = !enableOptimizations,
					IgnoreEval = ignoreEval,
					LineBreakPosition = lineBreakPosition,
					ObfuscateJavascript = obfuscateJavaScript,
					PreserveAllSemicolons = preserveAllSemiColons
				};
		}
 /// <summary>
 /// Filters the assets
 /// </summary>
 /// <param name="Assets">Assets to filter</param>
 /// <returns>The filtered assets</returns>
 public IList<IAsset> Filter(IList<IAsset> Assets)
 {
     if (Assets == null || Assets.Count == 0)
         return new List<IAsset>();
     if (Assets.FirstOrDefault().Type != AssetType.Javascript)
         return Assets;
     IEnumerable<IAsset> Processable = Assets.Where(x => !x.Minified);
     if (Processable.FirstOrDefault() == null)
         return Assets;
     var Minifier = new JavaScriptCompressor();
     foreach (IAsset Asset in Processable.Where(x => x != null))
     {
         try
         {
             Asset.Content = Minifier.Compress(Asset.Content);
             Asset.Minified = true;
         }
         catch { }
     }
     return Assets;
 }
Esempio n. 28
0
        static void Main(string[] args)
        {
            foreach (var arg in args)
                Console.WriteLine(arg);

            List<string> cssFiles = new List<string>();
            List<string> jsFiles = new List<string>();

            foreach (var file in args)
            {
                if (file.EndsWith(".css"))
                    cssFiles.Add(file);
                else if (file.EndsWith(".js"))
                    jsFiles.Add(file);
            }

            var cssCompressor = new CssCompressor();
            var jsCompressor = new JavaScriptCompressor();

            foreach(var jsFile in jsFiles){
                var compress = jsCompressor.Compress(File.ReadAllText(jsFile));
                var newPath = jsFile.Replace(".js", "") + ".min.js";
                using (StreamWriter swr = new StreamWriter(newPath,false))
                {
                    swr.Write(compress);
                    swr.Close();
                }
            }

            foreach (var cssFile in cssFiles)
            {
                var compress = cssCompressor.Compress(File.ReadAllText(cssFile));
                var newPath = cssFile.Replace(".css", "") + ".min.css";
                using (StreamWriter swr = new StreamWriter(newPath, false))
                {
                    swr.Write(compress);
                    swr.Close();
                }
            }
        }
Esempio n. 29
0
        static void Main(string[] args)
        {
            // Loads the build list
            ReadBuildList();

            // Collect all files in this directory
            var dir    = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var target = Path.Combine(dir, "UltimateLib.js");

            if (File.Exists(target))
            {
                File.Delete(target);
            }

            var files = new List <string>();


            foreach (var item in BuildList.Core.Items)
            {
                files.Add(Path.Combine(dir, "core\\" + item + ".js"));
            }

            foreach (var item in BuildList.Libraries3rd.Items)
            {
                files.Add(Path.Combine(dir, "3rd\\" + item + ".js"));
            }

            foreach (var item in BuildList.Libraries.Items)
            {
                files.Add(Path.Combine(dir, "libs\\" + item + ".js"));
            }

            files.Add(Path.Combine(dir, "GDT.Hook.js"));


            if (BuildList.Optimizations.Enabled)
            {
                var yuc = new Yahoo.Yui.Compressor.JavaScriptCompressor();
                var sb  = new StringBuilder();

                yuc.DisableOptimizations  = BuildList.Optimizations.DisableOptimizations;
                yuc.LoggingType           = LoggingType.None;
                yuc.LineBreakPosition     = 1;
                yuc.CompressionType       = BuildList.Optimizations.Compression? CompressionType.Standard : CompressionType.None;
                yuc.ObfuscateJavascript   = BuildList.Optimizations.Obfuscation;
                yuc.PreserveAllSemicolons = BuildList.Optimizations.PreserveAllSemicolons;
                yuc.IgnoreEval            = BuildList.Optimizations.IgnoreEval;

                try
                {
                    foreach (var file in files)
                    {
                        if (!File.Exists(file))
                        {
                            continue;
                        }


                        sb.Append(yuc.Compress(File.ReadAllText(file)));
                    }



                    using (var output = File.CreateText(target))
                    {
                        output.Write(sb.ToString());
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error " + ex.Message);
                }
            }
            else
            {
                const int chunkSize = 2 * 1024; // 2KB
                using (var output = File.Create(target))
                {
                    foreach (var file in files)
                    {
                        if (!File.Exists(file))
                        {
                            continue;
                        }
                        using (var input = File.OpenRead(file))
                        {
                            var buffer = new byte[chunkSize];
                            int bytesRead;
                            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                output.Write(buffer, 0, bytesRead);
                            }
                        }
                    }
                }
            }
        }
        public static string Compress(string javaScript,
                                      bool isVerboseLogging,
                                      bool isObfuscateJavascript,
                                      bool preserveAllSemicolons,
                                      bool disableOptimizations,
                                      int lineBreakPosition,
                                      Encoding encoding,
                                      CultureInfo threadCulture,
                                      bool isEvalIgnored)
        {
            if (string.IsNullOrEmpty(javaScript))
            {
                throw new ArgumentNullException("javaScript");
            }

            var javaScriptCompressor = new JavaScriptCompressor(javaScript,
                                                                isVerboseLogging,
                                                                encoding,
                                                                threadCulture,
                                                                isEvalIgnored,
                                                                null);

            return javaScriptCompressor.Compress(isObfuscateJavascript,
                                                 preserveAllSemicolons,
                                                 disableOptimizations,
                                                 lineBreakPosition);
        }
Esempio n. 31
0
 public JsMinifyCompiler()
 {
     _compiler = new JavaScriptCompressor();
 }
        private string TransformContent(BundleResource bundleResource, HttpContext context)
        {
            var bundleType = bundleResource.Type;
            var content = bundleResource.Content;
            var serverpath = bundleResource.ServerPath;

            try
            {
                if (bundleType == BundleResourceType.EmbeddedScript || bundleType == BundleResourceType.ScriptFile)
                {
                    var compressor = new JavaScriptCompressor
                    {
                        CompressionType = CompressionType.Standard,
                        Encoding = Encoding.UTF8,
                        ObfuscateJavascript = bundleResource.ObfuscateJs
                    };


                    //Minimize
                    var contentOut = compressor.Compress(content.Trim()) + ";";

                    //Return deffered execution
                    if (ClientSettings.IsJavascriptDefferingEnabled)
                    {
                        return string.Format(ClientSettings.JavascriptDefferingScript,
                                      JsonConvert.SerializeObject(contentOut));
                    }
                    return contentOut;
                }
                if (!string.IsNullOrEmpty(serverpath))
                {
                    string directoryName = Path.GetDirectoryName(serverpath);
                    if (directoryName != null)
                        serverpath = directoryName.Replace('\\', '/');
                }
                if (bundleType == BundleResourceType.EmbeddedStyle || bundleType == BundleResourceType.StyleFile)
                {
                    var compressor = new CssCompressor
                                         {
                                             CompressionType = CompressionType.Standard,
                                             RemoveComments = true
                                         };

                    return ReplaceUrls(compressor.Compress(content), serverpath, context);
                }
                if (bundleType == BundleResourceType.LessFile)
                {
                    DotlessConfiguration cfg = DotlessConfiguration.GetDefaultWeb();
                    cfg.Web = true;
                    cfg.MinifyOutput = true;
                    cfg.MapPathsToWeb = true;
                    cfg.CacheEnabled = false;

                    //Prefilter
                    content = ReplaceImportRegex.Replace(content, match => ReplaceImports(match, serverpath));
                    string processed = ReplaceUrls(LessWeb.Parse(content, cfg), serverpath, context);
                    return processed;
                }
            }
            catch (EcmaScript.NET.EcmaScriptException e)
            {
                _log.ErrorFormat("EcmaScriptException: {0} in {1} at {2} ({3}, {4}) at ", e.Message, serverpath, e.LineSource, e.LineNumber, e.ColumnNumber, e.ScriptStackTrace);
            }
            catch (Exception e)
            {
                _log.Error(e);
            }
            return content;
        }