Exemple #1
0
        public void RelativePaths()
        {
            UglifyResult result;

            string sFileContent = @"function test(t){
	return t**2;
}";

            var builder = new StringBuilder();

            using (TextWriter mapWriter = new StringWriter(builder))
            {
                using (var sourceMap = new V3SourceMap(mapWriter))
                {
                    sourceMap.MakePathsRelative = false;

                    var settings = new CodeSettings();
                    settings.SymbolsMap = sourceMap;
                    sourceMap.StartPackage(@"C:\some\long\path\to\js", @"C:\some\other\path\to\map");

                    result = Uglify.Js(sFileContent, @"C:\some\path\to\output\js", settings);
                }
            }

            Assert.AreEqual("function test(n){return n**2}\n//# sourceMappingURL=C:\\some\\other\\path\\to\\map\n", result.Code);

            Assert.AreEqual("{\r\n\"version\":3,\r\n\"file\":\"C:\\some\\long\\path\\to\\js\",\r\n\"mappings\":\"AAAAA,SAASA,IAAI,CAACC,CAAD,CAAG,CACf,OAAOA,CAAC,EAAE,CADK\",\r\n\"sources\":[\"C:\\some\\path\\to\\output\\js\"],\r\n\"names\":[\"test\",\"t\"]\r\n}\r\n", builder.ToString());
        }
Exemple #2
0
        private async static Task <bool> MinifyFileWithSourceMap(string file, string minFile)
        {
            bool         result;
            string       mapPath = minFile + ".map";
            StringWriter writer  = new StringWriter();

            ProjectHelpers.CheckOutFileFromSourceControl(mapPath);

            using (V3SourceMap sourceMap = new V3SourceMap(writer))
            {
                var settings = CreateSettings();

                settings.SymbolsMap = sourceMap;
                sourceMap.StartPackage(minFile, mapPath);

                // This fails when debugger is attached. Bug raised with Ron Logan
                result = await MinifyFile(file, minFile, settings);
            }

            await FileHelpers.WriteAllTextRetry(mapPath, writer.ToString(), false);

            ProjectHelpers.AddFileToProject(minFile, mapPath);

            return(result);
        }
Exemple #3
0
        private void Minify(string jsPath)
        {
            string minifiedPath = null;

            if (jsPath.EndsWith(".js", StringComparison.OrdinalIgnoreCase) == false)
            {
                minifiedPath = jsPath + ".min";
            }
            else
            {
                minifiedPath = jsPath.Substring(0, jsPath.Length - 3) + ".min.js";
            }

            var mapPath = jsPath.Replace(".js", ".min.js") + ".map";

            StreamWriter mapWriter = null;
            V3SourceMap  sourceMap = null;

            try
            {
                var settings = new CodeSettings();
                //try
                //{
                //Be aware that the text encoding should be UTF-8 with no Byte-Order Mark (BOM) written at the beginning.
                //V3 source map files that include a BOM will not be read by Chrome
                mapWriter = new StreamWriter(mapPath, false, new System.Text.UTF8Encoding(false));
                sourceMap = new V3SourceMap(mapWriter);
                sourceMap.StartPackage(minifiedPath, mapPath);
                // the first argument specifies "file" field in map file.
                // the second arugment specifies "//# sourceMappingURL=" in the output (minified js)
                settings.SymbolsMap = sourceMap;
                //}
                //catch (Exception ex)
                //{
                //}


                settings.TermSemicolons = true;
                Minifier minifier = new Minifier();
                minifier.FileName = jsPath;
                var content = minifier.MinifyJavaScript(File.ReadAllText(jsPath), settings);

                using (StreamWriter sw = new StreamWriter(minifiedPath))
                {
                    sw.Write(content);
                }
            }
            finally
            {
                if (sourceMap != null)
                {
                    sourceMap.EndPackage();
                    sourceMap.Dispose();
                }
                mapWriter?.Dispose();
            }
        }
Exemple #4
0
        /// <summary>
        /// Creates a new inline source map
        /// </summary>
        /// <param name="wrapped"></param>
        /// <param name="mapBuilder"></param>
        /// <param name="sourceSourceMapType"></param>
        public V3DeferredSourceMap(V3SourceMap wrapped, StringBuilder mapBuilder, SourceMapType sourceSourceMapType)
        {
            if (wrapped == null)
            {
                throw new ArgumentNullException(nameof(wrapped));
            }
            if (mapBuilder == null)
            {
                throw new ArgumentNullException(nameof(mapBuilder));
            }

            _wrapped      = wrapped;
            _mapBuilder   = mapBuilder;
            SourceMapType = sourceSourceMapType;
        }
Exemple #5
0
        public void CallMinifyAPI()
        {
            var sourcePath = @"someSource.js";
            var mapPath    = @"someSource.map.js";

            // just some random source
            var sourceCode = "var foo = 42;function globalFunc(text){ alert(text); }";

            string minifiedCode = null;

            var mapBuilder = new StringBuilder();

            using (var mapWriter = new StringWriter(mapBuilder))
            {
                using (var sourceMap = new V3SourceMap(mapWriter))
                {
                    var settings = new CodeSettings();
                    settings.SymbolsMap = sourceMap;
                    sourceMap.StartPackage(sourcePath, mapPath);

                    var minifier = new Minifier();
                    minifiedCode = minifier.MinifyJavaScript(sourceCode, settings);
                }
            }

            // just verify that we got some source map content
            var mapContent = mapBuilder.ToString();

            Assert.IsNotNull(mapContent, "map content should not be null");
            Assert.IsFalse(mapContent.IsNullOrWhiteSpace(), "map content should not be empty");

            // better have some minified code results
            Assert.IsNotNull(minifiedCode, "minified code should not be null");

            // verify the code UP TO the first line break, since the comment should be added on a new line and there
            // shouldn't be any linebreaks other than that.
            var indexLineBreak = minifiedCode.IndexOf('\n');
            var trimmedCode    = indexLineBreak < 0 ? minifiedCode : minifiedCode.Substring(0, indexLineBreak);

            Assert.AreEqual("function globalFunc(n){alert(n)}var foo=42", trimmedCode, "minified code not expected");

            // verify that the minified code has the sourceMappingURL directive in it
            Assert.IsTrue(minifiedCode.Contains("sourceMappingURL=" + mapPath), "sourceMappingURL should be in minified content");
        }
Exemple #6
0
        public void Bug199_SourceMap()
        {
            UglifyResult result;

            string sFileContent = @"define(""moment"", [], function() { return (function(modules) { })
({
	/***/ ""./node_modules/moment/locale sync recursive ^\\.\\/.*$"":
	/*! no static exports found */
	/***/ (function(module, exports, __webpack_require__) { } ) } ) } )"    ;

            var builder = new StringBuilder();

            using (TextWriter mapWriter = new StringWriter(builder))
            {
                using (var sourceMap = new V3SourceMap(mapWriter))
                {
                    sourceMap.MakePathsRelative = false;

                    var settings = new CodeSettings();
                    settings.SymbolsMap = sourceMap;
                    sourceMap.StartPackage(@"C:\some\long\path\to\js", @"C:\some\other\path\to\map");

                    result = Uglify.Js(sFileContent, @"C:\some\path\to\output\js", settings);
                }
            }

            var expected = @"define(""moment"",[],function(){return function(){}({""./node_modules/moment/locale sync recursive ^\\.\\/.*$"":function(){}})})
//# sourceMappingURL=C:\some\other\path\to\map
";

            Assert.AreEqual(expected, result.Code);

            var actual = builder.ToString();

            Assert.AreEqual(@"{
""version"":3,
""file"":""C:\\some\\long\\path\\to\\js"",
""mappings"":""AAAAA,MAAM,CAAC,QAAQ,CAAE,CAAA,CAAE,CAAE,QAAQ,CAAA,CAAG,CAAE,OAAQ,QAAQ,CAAA,CAAU,EAC5D,CAAC,CACM,wDAAwD,CAEvDC,QAAQ,CAAA,CAAuC,EAHtD,CAAD,CADgC,CAA1B"",
""sources"":[""C:\\some\\path\\to\\output\\js""],
""names"":[""define"",""./node_modules/moment/locale sync recursive ^\\.\\/.*$""]
}
".Replace("\n", "\r\n"), actual);
        }
Exemple #7
0
        private static void MinifyJavaScript(Bundle bundle, MinificationResult minResult)
        {
            var settings = JavaScriptOptions.GetSettings(bundle);

            if (!bundle.SourceMap)
            {
                var uglifyResult = Uglify.Js(bundle.Output, settings);
                WriteMinFile(bundle, minResult, uglifyResult);
            }
            else
            {
                string minFile = GetMinFileName(minResult.FileName);
                string mapFile = minFile + ".map";

                using (StringWriter writer = new StringWriter())
                {
                    using (V3SourceMap sourceMap = new V3SourceMap(writer))
                    {
                        settings.SymbolsMap = sourceMap;
                        sourceMap.StartPackage(minFile, mapFile);
                        sourceMap.SourceRoot = bundle.SourceMapRootPath;

                        string file = minResult.FileName;

                        if (bundle.OutputIsMinFile)
                        {
                            var inputs = bundle.GetAbsoluteInputFiles();

                            if (inputs.Count == 1)
                            {
                                file = inputs[0];
                            }
                        }

                        var uglifyResult = Uglify.Js(bundle.Output, file, settings);
                        WriteMinFile(bundle, minResult, uglifyResult);
                    }

                    minResult.SourceMap = writer.ToString();
                }
            }
        }
        private static bool MinifyFileWithSourceMap(string file, string minFile)
        {
            string mapPath = minFile + ".map";

            ProjectHelpers.CheckOutFileFromSourceControl(mapPath);

            using (TextWriter writer = new StreamWriter(mapPath, false, new UTF8Encoding(false)))
                using (V3SourceMap sourceMap = new V3SourceMap(writer))
                {
                    var settings = CreateSettings();
                    settings.SymbolsMap = sourceMap;
                    sourceMap.StartPackage(Path.GetFileName(minFile), Path.GetFileName(mapPath));

                    // This fails when debugger is attached. Bug raised with Ron Logan
                    bool result = MinifyFile(file, minFile, settings);
                    ProjectHelpers.AddFileToProject(minFile, mapPath);

                    return(result);
                }
        }
Exemple #9
0
        public void SourceMapForMultipleFiles()
        {
            var assetBuilder = new StringBuilder();
            var assets       = new[] { "SourceMapForMultipleFiles1.js", "SourceMapForMultipleFiles2.js", "SourceMapForMultipleFiles3.js" };

            var currentPath = AppDomain.CurrentDomain.BaseDirectory;

            foreach (var asset in assets)
            {
                assetBuilder.AppendLine("///#source 1 1 " + asset);
                var path = Path.Combine(currentPath, "TestData\\JS\\Input\\SourceMap\\" + asset);
                assetBuilder.AppendLine(File.ReadAllText(path));
            }

            var stringBuilder = new StringBuilder();

            using (var textWriter = new StringWriter(stringBuilder))
            {
                var sourceMap = new V3SourceMap(textWriter);

                sourceMap.StartPackage("infile.js", "SourceMapForMultipleFiles.js.map");
                var uglifyResult = Uglify.Js(assetBuilder.ToString(), "SourceMapForMultipleFiles.js", new CodeSettings
                {
                    SymbolsMap           = sourceMap,
                    SourceMode           = JavaScriptSourceMode.Program,
                    MinifyCode           = true,
                    OutputMode           = OutputMode.SingleLine,
                    StripDebugStatements = false,
                    LineTerminator       = "\r\n"
                });
                sourceMap.EndPackage();
                sourceMap.Dispose();

                var code = uglifyResult.Code;
                Assert.AreEqual(File.ReadAllText(Path.Combine(currentPath, "TestData\\JS\\Expected\\SourceMap\\SourceMapForMultipleFiles.js")), code);
                var builder = stringBuilder.ToString();
                Assert.AreEqual(File.ReadAllText(Path.Combine(currentPath, "TestData\\JS\\Expected\\SourceMap\\SourceMapForMultipleFiles.js.map")), builder);
            }
        }
        private static void MinifyFileWithSourceMap(string file, string minFile, CodeSettings settings, bool isBundle)
        {
            bool useBom    = WESettings.GetBoolean(WESettings.Keys.UseBom);
            string mapPath = minFile + ".map";

            ProjectHelpers.CheckOutFileFromSourceControl(mapPath);
            using (TextWriter writer = new StreamWriter(mapPath, false, new UTF8Encoding(useBom)))
            using (V3SourceMap sourceMap = new V3SourceMap(writer))
            {
                settings.SymbolsMap = sourceMap;

                sourceMap.StartPackage(Path.GetFileName(minFile), Path.GetFileName(mapPath));

                // This fails when debugger is attached. Bug raised with Ron Logan
                MinifyFile(file, minFile, settings, isBundle);

                sourceMap.EndPackage();

                if (!isBundle)
                {
                    MarginBase.AddFileToProject(file, mapPath);
                }
            }
        }
Exemple #11
0
        private static void MinifyFileWithSourceMap(string file, string minFile, CodeSettings settings, bool isBundle)
        {
            string mapPath = minFile + ".map";

            ProjectHelpers.CheckOutFileFromSourceControl(mapPath);

            using (TextWriter writer = new StreamWriter(mapPath, false, new UTF8Encoding(false)))
                using (V3SourceMap sourceMap = new V3SourceMap(writer))
                {
                    settings.SymbolsMap = sourceMap;

                    sourceMap.StartPackage(Path.GetFileName(minFile), Path.GetFileName(mapPath));

                    // This fails when debugger is attached. Bug raised with Ron Logan
                    MinifyFile(file, minFile, settings, isBundle);

                    sourceMap.EndPackage();

                    if (!isBundle)
                    {
                        MarginBase.AddFileToProject(file, mapPath);
                    }
                }
        }
Exemple #12
0
        public override IEnumerable <PvcCore.PvcStream> Execute(IEnumerable <PvcCore.PvcStream> inputStreams)
        {
            var          resultStreams = new List <PvcStream>();
            SwitchParser switchParser  = null;

            if (!String.IsNullOrEmpty(this.commandLineSwitches))
            {
                switchParser = new SwitchParser();
                switchParser.Parse(this.commandLineSwitches);
            }

            foreach (var inputStream in inputStreams)
            {
                var dirName      = Path.GetDirectoryName(inputStream.StreamName);
                var fileName     = Path.GetFileNameWithoutExtension(inputStream.StreamName) + ".min" + Path.GetExtension(inputStream.StreamName);
                var resultName   = Path.Combine(dirName, fileName);
                var fileContent  = new StreamReader(inputStream).ReadToEnd();
                var minifier     = new Minifier();
                var sourceStream = new MemoryStream();
                var outputWriter = new StreamWriter(sourceStream);

                if (inputStream.StreamName.EndsWith(".js"))
                {
                    // Currently AjaxMin only supports JS source maps
                    if (this.generateSourceMaps)
                    {
                        var resultMapName = resultName + ".map";
                        var utf8          = new UTF8Encoding(false);
                        var mapStream     = new MemoryStream();
                        var mapWriter     = new SourcemapStreamWriter(mapStream, utf8);
                        var sourceMap     = new V3SourceMap(mapWriter);

                        if (sourceMap != null)
                        {
                            if (switchParser == null)
                            {
                                switchParser = new SwitchParser();
                            }

                            switchParser.JSSettings.SymbolsMap     = sourceMap;
                            switchParser.JSSettings.TermSemicolons = true;

                            sourceMap.StartPackage(resultName, resultMapName);

                            outputWriter.Write(minifier.MinifyJavaScript(fileContent, switchParser.JSSettings));

                            sourceMap.EndPackage();
                            sourceMap.EndFile(outputWriter, "\r\n");

                            sourceMap.Dispose();
                            mapWriter.Flush();

                            resultStreams.Add(new PvcStream(() => mapStream).As(resultMapName));
                        }
                    }
                    else
                    {
                        CodeSettings settings = new CodeSettings();
                        if (switchParser != null)
                        {
                            settings = switchParser.JSSettings;
                        }
                        outputWriter.Write(minifier.MinifyJavaScript(fileContent, settings));
                    }
                }
                else
                {
                    CssSettings settings = new CssSettings();
                    if (switchParser != null)
                    {
                        settings = switchParser.CssSettings;
                    }
                    outputWriter.Write(minifier.MinifyStyleSheet(fileContent, settings));
                }

                foreach (var error in minifier.ErrorList)
                {
                    Console.Error.WriteLine(error.ToString());
                }

                outputWriter.Flush();
                resultStreams.Add(new PvcStream(() => sourceStream).As(resultName));
            }

            return(resultStreams);
        }
Exemple #13
0
        public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable <BundleFile> files)
        {
            if (files == null)
            {
                return(string.Empty);
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            // Generates source map using an approach documented here: http://ajaxmin.codeplex.com/discussions/446616
            var sourcePath     = VirtualPathUtility.ToAbsolute(bundle.Path);
            var mapVirtualPath = string.Concat(bundle.Path, "map"); // don't use .map so it's picked up by the bundle module
            var mapPath        = VirtualPathUtility.ToAbsolute(mapVirtualPath);

            // Concatenate file contents to be minified, including the sourcemap hints
            var contentConcatedString = GetContentConcated(context, files);

            // Try minify (+ source map) using AjaxMin dll
            try
            {
                var contentBuilder = new StringBuilder();
                var mapBuilder     = new StringBuilder();
                using (var contentWriter = new StringWriter(contentBuilder))
                    using (var mapWriter = new StringWriter(mapBuilder))
                        using (var sourceMap = new V3SourceMap(mapWriter))
                        {
                            var settings = new CodeSettings()
                            {
                                EvalTreatment             = EvalTreatment.MakeImmediateSafe,
                                PreserveImportantComments = false,
                                SymbolsMap     = sourceMap,
                                TermSemicolons = true,
                                MinifyCode     = minifyCode
                            };

                            sourceMap.StartPackage(sourcePath, mapPath);

                            var    minifier        = new Minifier();
                            string contentMinified = minifier.MinifyJavaScript(contentConcatedString, settings);
                            if (minifier.ErrorList.Count > 0)
                            {
                                return(GenerateMinifierErrorsContent(contentConcatedString, minifier));
                            }

                            contentWriter.Write(contentMinified);
                        }

                // Write the SourceMap to another Bundle
                AddContentToAdHocBundle(context, mapVirtualPath, mapBuilder.ToString());

                // Note: A current bug in AjaxMin reported by @LodewijkSioen here https://ajaxmin.codeplex.com/workitem/21834,
                // causes the MinifyJavascript method call to hang when debugger is attached if the following line is included.
                // To avoid more harm than good, don't support source mapping in this scenario until AjaxMin fixes it's bug.
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    contentBuilder.Insert(0, sourceMappingDisabledMsg + "\r\n\r\n\r\n");
                }

                return(contentBuilder.ToString());
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("An exception occurred trying to build bundle contents for bundle with virtual path: " + bundle.Path + ". See Exception details.", ex, typeof(ScriptWithSourceMapBundleBuilder));
                return(GenerateGenericErrorsContent(contentConcatedString));
            }
        }
        public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
        {
            if (files == null)
            {
                return string.Empty;
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            // Generates source map using an approach documented here: http://ajaxmin.codeplex.com/discussions/446616
            var sourcePath = VirtualPathUtility.ToAbsolute(bundle.Path);
            var mapVirtualPath = string.Concat(bundle.Path, "map"); // don't use .map so it's picked up by the bundle module
            var mapPath = VirtualPathUtility.ToAbsolute(mapVirtualPath);

            // Concatenate file contents to be minified, including the sourcemap hints
            var contentConcatedString = GetContentConcated(context, files);

            // Try minify (+ source map) using AjaxMin dll
            try
            {
                var contentBuilder = new StringBuilder();
                var mapBuilder = new StringBuilder();
                using (var contentWriter = new StringWriter(contentBuilder))
                using (var mapWriter = new StringWriter(mapBuilder))
                using (var sourceMap = new V3SourceMap(mapWriter))
                {
                    var settings = new CodeSettings()
                    {
                        EvalTreatment = EvalTreatment.MakeImmediateSafe,
                        PreserveImportantComments = false,
                        SymbolsMap = sourceMap,
                        TermSemicolons = true
                    };

                    sourceMap.StartPackage(sourcePath, mapPath);

                    var minifier = new Minifier();
                    string contentMinified = minifier.MinifyJavaScript(contentConcatedString, settings);
                    if (minifier.ErrorList.Count > 0)
                    {
                        return GenerateMinifierErrorsContent(contentConcatedString, minifier);
                    }

                    contentWriter.Write(contentMinified);
                }

                // Write the SourceMap to another Bundle
                AddContentToAdHocBundle(context, mapVirtualPath, mapBuilder.ToString());

                // Note: A current bug in AjaxMin reported by @LodewijkSioen here https://ajaxmin.codeplex.com/workitem/21834,
                // causes the MinifyJavascript method call to hang when debugger is attached if the following line is included.
                // To avoid more harm than good, don't support source mapping in this scenario until AjaxMin fixes it's bug.
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    contentBuilder.Insert(0, sourceMappingDisabledMsg + "\r\n\r\n\r\n");
                }

                return contentBuilder.ToString();
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("An exception occurred trying to build bundle contents for bundle with virtual path: " + bundle.Path + ". See Exception details.", ex, typeof(ScriptWithSourceMapBundleBuilder));
                return GenerateGenericErrorsContent(contentConcatedString);
            }
        }
        public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable <BundleFile> files)
        {
            if (files == null)
            {
                return(string.Empty);
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            // Generates source map using an approach documented here: http://ajaxmin.codeplex.com/discussions/446616
            var sourcePath     = VirtualPathUtility.ToAbsolute(bundle.Path);
            var mapVirtualPath = string.Concat(bundle.Path, "map"); // don't use .map so it's picked up by the bundle module
            var mapPath        = VirtualPathUtility.ToAbsolute(mapVirtualPath);

            // Concatenate file contents to be minified, including the sourcemap hints
            var contentConcatedString = GetContentConcated(context, files);

            // Try minify (+ source map) using AjaxMin dll
            try
            {
                var contentBuilder = new StringBuilder();
                var mapBuilder     = new StringBuilder();
                using (var contentWriter = new StringWriter(contentBuilder))
                    using (var mapWriter = new StringWriter(mapBuilder))
                        using (var sourceMap = new V3SourceMap(mapWriter))
                        {
                            var settings = new CodeSettings()
                            {
                                EvalTreatment             = EvalTreatment.MakeImmediateSafe,
                                PreserveImportantComments = preserveImportantComments,
                                SymbolsMap     = sourceMap,
                                TermSemicolons = true,
                                MinifyCode     = minifyCode
                            };

                            sourceMap.StartPackage(sourcePath, mapPath);

                            var    result          = Uglify.Js(contentConcatedString, settings);
                            string contentMinified = result.Code;
                            if (result.Errors.Count > 0)
                            {
                                return(GenerateMinifierErrorsContent(contentConcatedString, result));
                            }

                            contentWriter.Write(contentMinified);
                        }

                // Write the SourceMap to another Bundle
                AddContentToAdHocBundle(context, mapVirtualPath, mapBuilder.ToString());

                return(contentBuilder.ToString());
            }
            catch (Exception ex)
            {
                // only Trace the fact that an exception occurred to the Warning output, but use Informational tracing for added detail for diagnosis
                Trace.TraceWarning("An exception occurred trying to build bundle contents for bundle with virtual path: " + bundle.Path + ". See Exception details in Information.");

                string bundlePrefix = "[Bundle '" + bundle.Path + "']";
                Trace.TraceInformation(bundlePrefix + " exception message: " + ex.Message);

                if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                {
                    Trace.TraceInformation(bundlePrefix + " inner exception message: " + ex.InnerException.Message);
                }

                Trace.TraceInformation(bundlePrefix + " source: " + ex.Source);
                Trace.TraceInformation(bundlePrefix + " stack trace: " + ex.StackTrace);

                return(GenerateGenericErrorsContent(contentConcatedString));
            }
        }
        private static MinificationResult MinifyJavaScript(Bundle bundle)
        {
            string file = bundle.GetAbsoluteOutputFile();
            var settings = JavaScriptOptions.GetSettings(bundle);
            var minifier = new Minifier();
            var result = new MinificationResult(file, null, null);

            string minFile = GetMinFileName(file);
            string mapFile = minFile + ".map";

            try
            {
                if (!bundle.SourceMaps)
                {
                    result.MinifiedContent = minifier.MinifyJavaScript(File.ReadAllText(file), settings);

                    if (!minifier.Errors.Any())
                    {
                        OnBeforeWritingMinFile(file, minFile, bundle);
                        File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(true));
                        OnAfterWritingMinFile(file, minFile, bundle);
                    }
                    else
                    {
                        FileMinifier.AddAjaxminErrors(minifier, result);
                    }
                }
                else
                {
                    using (StringWriter writer = new StringWriter())
                    {
                        using (V3SourceMap sourceMap = new V3SourceMap(writer))
                        {
                            settings.SymbolsMap = sourceMap;
                            sourceMap.StartPackage(minFile, mapFile);

                            minifier.FileName = file;
                            result.MinifiedContent = minifier.MinifyJavaScript(File.ReadAllText(file), settings);

                            if (!minifier.Errors.Any())
                            {
                                OnBeforeWritingMinFile(file, minFile, bundle);
                                File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(true));
                                OnAfterWritingMinFile(file, minFile, bundle);
                            }
                            else
                            {
                                FileMinifier.AddAjaxminErrors(minifier, result);
                            }
                        }

                        result.SourceMap = writer.ToString();
                    }
                }

                GzipFile(minFile, bundle);
            }
            catch (Exception ex)
            {
                result.Errors.Add(new MinificationError
                {
                    FileName = file,
                    Message = ex.Message,
                    LineNumber = 0,
                    ColumnNumber = 0
                });
            }

            return result;
        }
        private static MinificationResult MinifyJavaScript(Bundle bundle)
        {
            string file     = bundle.GetAbsoluteOutputFile();
            var    settings = JavaScriptOptions.GetSettings(bundle);
            var    minifier = new Minifier();
            var    result   = new MinificationResult(file, null, null);

            string minFile = GetMinFileName(file);
            string mapFile = minFile + ".map";

            try
            {
                if (!bundle.SourceMap)
                {
                    result.MinifiedContent = minifier.MinifyJavaScript(ReadAllText(file), settings).Trim();

                    if (!minifier.Errors.Any())
                    {
                        bool containsChanges = FileHelpers.HasFileContentChanged(minFile, result.MinifiedContent);

                        OnBeforeWritingMinFile(file, minFile, bundle, containsChanges);

                        if (containsChanges)
                        {
                            File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(false));
                        }

                        GzipFile(minFile, bundle, containsChanges);

                        OnAfterWritingMinFile(file, minFile, bundle, containsChanges);
                    }
                    else
                    {
                        AddAjaxminErrors(minifier, result);
                    }
                }
                else
                {
                    using (StringWriter writer = new StringWriter())
                    {
                        using (V3SourceMap sourceMap = new V3SourceMap(writer))
                        {
                            settings.SymbolsMap = sourceMap;
                            sourceMap.StartPackage(minFile, mapFile);

                            minifier.FileName      = file;
                            result.MinifiedContent = minifier.MinifyJavaScript(ReadAllText(file), settings).Trim();

                            if (!minifier.Errors.Any())
                            {
                                bool containsChanges = FileHelpers.HasFileContentChanged(minFile, result.MinifiedContent);

                                OnBeforeWritingMinFile(file, minFile, bundle, containsChanges);

                                if (containsChanges)
                                {
                                    File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(false));
                                }

                                OnAfterWritingMinFile(file, minFile, bundle, containsChanges);

                                GzipFile(minFile, bundle, containsChanges);
                            }
                            else
                            {
                                AddAjaxminErrors(minifier, result);
                            }
                        }

                        result.SourceMap = writer.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                result.Errors.Add(new MinificationError
                {
                    FileName     = file,
                    Message      = ex.Message,
                    LineNumber   = 0,
                    ColumnNumber = 0
                });
            }

            return(result);
        }
Exemple #18
0
        public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable <BundleFile> files)
        {
            if (files == null)
            {
                return(string.Empty);
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }

            // Generates source map using an approach documented here: http://ajaxmin.codeplex.com/discussions/446616

            // Get paths and create any directories required
            var mapVirtualPath = bundle.Path + ".map";
            var sourcePath     = HostingEnvironment.MapPath(bundle.Path);
            var mapPath        = HostingEnvironment.MapPath(mapVirtualPath);
            var directoryPath  = Path.GetDirectoryName(mapPath);

            if (directoryPath == null)
            {
                throw new InvalidOperationException("directoryPath was invalid.");
            }

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            // Concatenate file contents to be minified, including the sourcemap hints
            var contentConcated = new StringBuilder();

            foreach (var file in files)
            {
                var filePath = HostingEnvironment.MapPath(file.VirtualFile.VirtualPath);
                if (bundleFileType == BundleFileTypes.JavaScript)
                {
                    contentConcated.AppendLine(";///#SOURCE 1 1 " + filePath);
                }
                contentConcated.AppendLine(file.ApplyTransforms());
            }
            var contentConcatedString = contentConcated.ToString();

            // Try minify (+ source map) using AjaxMin dll
            try
            {
                var contentBuilder = new StringBuilder();
                using (var contentWriter = new StringWriter(contentBuilder))
                    using (var mapWriter = new StreamWriter(mapPath, false, new UTF8Encoding(false)))
                        using (var sourceMap = new V3SourceMap(mapWriter))
                        {
                            sourceMap.StartPackage(sourcePath, mapPath);

                            var settings = new CodeSettings()
                            {
                                EvalTreatment             = EvalTreatment.MakeImmediateSafe,
                                PreserveImportantComments = false,
                                SymbolsMap     = sourceMap,
                                TermSemicolons = true
                            };

                            var    minifier = new Minifier();
                            string contentMinified;
                            switch (bundleFileType)
                            {
                            case BundleFileTypes.JavaScript:
                                contentMinified = minifier.MinifyJavaScript(contentConcatedString, settings);
                                break;

                            case BundleFileTypes.StyleSheet:
                                var cssSettings = new CssSettings
                                {
                                    TermSemicolons = true
                                };
                                contentMinified = minifier.MinifyStyleSheet(contentConcatedString, cssSettings, settings);
                                break;

                            default:
                                throw new ArgumentOutOfRangeException("Unrecognised BundleFileTypes enum value. Could not find minifier method to handle.");
                            }
                            if (minifier.ErrorList.Count > 0)
                            {
                                return(GenerateMinifierErrorsContent(contentConcatedString, minifier));
                            }

                            contentWriter.Write(contentMinified);

                            sourceMap.EndPackage();
                            sourceMap.EndFile(contentWriter, "\r\n");
                        }

                return(contentBuilder.ToString());
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("An exception occurred trying to build bundle contents for bundle with virtual path: " + bundle.Path + ". See Exception details.", ex, typeof(AjaxMinBundleBuilder));
                return(GenerateGenericErrorsContent(contentConcatedString));
            }
        }
        private async static Task<bool> MinifyFileWithSourceMap(string file, string minFile)
        {
            bool result;
            string mapPath = minFile + ".map";
            StringWriter writer = new StringWriter();

            ProjectHelpers.CheckOutFileFromSourceControl(mapPath);

            using (V3SourceMap sourceMap = new V3SourceMap(writer))
            {
                var settings = CreateSettings();

                settings.SymbolsMap = sourceMap;
                sourceMap.StartPackage(minFile, mapPath);

                result = await MinifyFile(file, minFile, settings);
            }

            await FileHelpers.WriteAllTextRetry(mapPath, writer.ToString(), false);

            ProjectHelpers.AddFileToProject(minFile, mapPath);

            return result;
        }
        private static MinificationResult MinifyJavaScript(string file, bool produceGzipFile, bool produceSourceMap)
        {
            var settings = new CodeSettings()
            {
                EvalTreatment = EvalTreatment.Ignore,
                TermSemicolons = true,
                PreserveImportantComments = false,
            };

            var minifier = new Minifier();
            var result = new MinificationResult(file, null, null);

            string minFile = GetMinFileName(file);
            string mapFile = minFile + ".map";

            try
            {
                if (!produceSourceMap)
                {
                    result.MinifiedContent = minifier.MinifyJavaScript(File.ReadAllText(file), settings);

                    if (!minifier.Errors.Any())
                    {
                        OnBeforeWritingMinFile(file, minFile);
                        File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(true));
                        OnAfterWritingMinFile(file, minFile);
                    }
                    else
                    {
                        AddAjaxminErrors(minifier, result);
                    }
                }
                else
                {
                    using (StringWriter writer = new StringWriter())
                    {
                        using (V3SourceMap sourceMap = new V3SourceMap(writer))
                        {
                            settings.SymbolsMap = sourceMap;
                            sourceMap.StartPackage(minFile, mapFile);

                            minifier.FileName = file;
                            result.MinifiedContent = minifier.MinifyJavaScript(File.ReadAllText(file), settings);

                            if (!minifier.Errors.Any())
                            {
                                OnBeforeWritingMinFile(file, minFile);
                                File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(true));
                                OnAfterWritingMinFile(file, minFile);
                            }
                            else
                            {
                                AddAjaxminErrors(minifier, result);
                            }
                        }

                        result.SourceMap = writer.ToString();
                    }
                }

                if (produceGzipFile)
                    GzipFile(minFile);
            }
            catch (Exception ex)
            {
                result.Errors.Add(new MinificationError
                {
                    FileName = file,
                    Message = ex.Message,
                    LineNumber = 0,
                    ColumnNumber = 0
                });
            }

            return result;
        }
		/// <summary>
		/// Generate source map then minify file
		/// </summary>
		/// <param name="file"></param>
		/// <param name="minFile"></param>
		/// <param name="settings"></param>
		/// <param name="isBundle"></param>
		private static void MinifyFileWithSourceMap(string file, string minFile, CodeSettings settings, bool isBundle)
		{
			var fileName = minFile + ".map";

			using (var writer = new StreamWriter(fileName, false, new UTF8Encoding(false)))
			{
				using (var map = new V3SourceMap(writer))
				{
					settings.SymbolsMap = map;
					map.StartPackage(Path.GetFileName(minFile), Path.GetFileName(fileName));
					MinifyFile(file, minFile, settings, true, isBundle);
					map.EndPackage();
				}
			}

			Console.WriteLine("Source map generated: " + Path.GetFileName(fileName));
		}
Exemple #22
0
        private static MinificationResult MinifyJavaScript(Bundle bundle)
        {
            string file     = bundle.GetAbsoluteOutputFile();
            var    settings = JavaScriptOptions.GetSettings(bundle);
            var    result   = new MinificationResult(file, null, null);

            string minFile = GetMinFileName(file);
            string mapFile = minFile + ".map";

            try
            {
                if (!bundle.SourceMap)
                {
                    UgliflyResult uglifyResult;
                    try
                    {
                        uglifyResult = Uglify.Js(ReadAllText(file), settings);
                    }
                    catch
                    {
                        uglifyResult = new UgliflyResult(null,
                                                         new List <UglifyError> {
                            new UglifyError
                            {
                                IsError = true,
                                File    = file,
                                Message = "Error processing file"
                            }
                        });
                    }

                    result.MinifiedContent = uglifyResult.Code?.Trim();

                    if (!uglifyResult.HasErrors && !string.IsNullOrEmpty(result.MinifiedContent))
                    {
                        bool containsChanges = FileHelpers.HasFileContentChanged(minFile, result.MinifiedContent);

                        OnBeforeWritingMinFile(file, minFile, bundle, containsChanges);
                        result.Changed |= containsChanges;

                        if (containsChanges)
                        {
                            File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(false));
                            OnAfterWritingMinFile(file, minFile, bundle, containsChanges);
                        }

                        GzipFile(minFile, bundle, containsChanges);
                    }
                    else
                    {
                        AddAjaxminErrors(uglifyResult, result);
                    }
                }
                else
                {
                    using (StringWriter writer = new StringWriter())
                    {
                        using (V3SourceMap sourceMap = new V3SourceMap(writer))
                        {
                            settings.SymbolsMap = sourceMap;
                            sourceMap.StartPackage(minFile, mapFile);
                            sourceMap.SourceRoot = bundle.SourceMapRootPath;

                            if (file.EndsWith(".min.js"))
                            {
                                var inputs = bundle.GetAbsoluteInputFiles();

                                if (inputs.Count == 1)
                                {
                                    file = inputs[0];
                                }
                            }

                            UgliflyResult uglifyResult;
                            try
                            {
                                uglifyResult = Uglify.Js(ReadAllText(file), file, settings);
                            }
                            catch
                            {
                                uglifyResult = new UgliflyResult(null,
                                                                 new List <UglifyError> {
                                    new UglifyError
                                    {
                                        IsError = true,
                                        File    = file,
                                        Message = "Error processing file"
                                    }
                                });
                            }

                            result.MinifiedContent = uglifyResult.Code?.Trim();

                            if (!uglifyResult.HasErrors && !string.IsNullOrEmpty(result.MinifiedContent))
                            {
                                bool containsChanges = FileHelpers.HasFileContentChanged(minFile, result.MinifiedContent);
                                result.Changed |= containsChanges;
                                OnBeforeWritingMinFile(file, minFile, bundle, containsChanges);

                                if (containsChanges)
                                {
                                    File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(false));
                                    OnAfterWritingMinFile(file, minFile, bundle, containsChanges);
                                }


                                GzipFile(minFile, bundle, containsChanges);
                            }
                            else
                            {
                                AddAjaxminErrors(uglifyResult, result);
                            }
                        }

                        result.SourceMap = writer.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                result.Errors.Add(new MinificationError
                {
                    FileName     = file,
                    Message      = ex.Message,
                    LineNumber   = 0,
                    ColumnNumber = 0
                });
            }

            return(result);
        }
        private async static Task<bool> MinifyFileWithSourceMap(string file, string minFile)
        {
            string mapPath = minFile + ".map";
            ProjectHelpers.CheckOutFileFromSourceControl(mapPath);

            using (TextWriter writer = new StreamWriter(mapPath, false, new UTF8Encoding(false)))
            using (V3SourceMap sourceMap = new V3SourceMap(writer))
            {
                var settings = CreateSettings();
                settings.SymbolsMap = sourceMap;
                sourceMap.StartPackage(minFile, mapPath);

                // This fails when debugger is attached. Bug raised with Ron Logan
                bool result = await MinifyFile(file, minFile, settings);
                ProjectHelpers.AddFileToProject(minFile, mapPath);

                return result;
            }
        }
        private static MinificationResult MinifyJavaScript(string file, bool produceGzipFile, bool produceSourceMap)
        {
            var settings = new CodeSettings()
            {
                EvalTreatment             = EvalTreatment.Ignore,
                TermSemicolons            = true,
                PreserveImportantComments = false,
            };

            var minifier = new Minifier();
            var result   = new MinificationResult(file, null, null);

            string minFile = GetMinFileName(file);
            string mapFile = minFile + ".map";

            try
            {
                if (!produceSourceMap)
                {
                    result.MinifiedContent = minifier.MinifyJavaScript(File.ReadAllText(file), settings);

                    if (!minifier.Errors.Any())
                    {
                        OnBeforeWritingMinFile(file, minFile);
                        File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(true));
                        OnAfterWritingMinFile(file, minFile);
                    }
                    else
                    {
                        AddAjaxminErrors(minifier, result);
                    }
                }
                else
                {
                    using (StringWriter writer = new StringWriter())
                    {
                        using (V3SourceMap sourceMap = new V3SourceMap(writer))
                        {
                            settings.SymbolsMap = sourceMap;
                            sourceMap.StartPackage(minFile, mapFile);

                            minifier.FileName      = file;
                            result.MinifiedContent = minifier.MinifyJavaScript(File.ReadAllText(file), settings);

                            if (!minifier.Errors.Any())
                            {
                                OnBeforeWritingMinFile(file, minFile);
                                File.WriteAllText(minFile, result.MinifiedContent, new UTF8Encoding(true));
                                OnAfterWritingMinFile(file, minFile);
                            }
                            else
                            {
                                AddAjaxminErrors(minifier, result);
                            }
                        }

                        result.SourceMap = writer.ToString();
                    }
                }

                if (produceGzipFile)
                {
                    GzipFile(minFile);
                }
            }
            catch (Exception ex)
            {
                result.Errors.Add(new MinificationError
                {
                    FileName     = file,
                    Message      = ex.Message,
                    LineNumber   = 0,
                    ColumnNumber = 0
                });
            }

            return(result);
        }
Exemple #25
0
        public override IEnumerable<PvcCore.PvcStream> Execute(IEnumerable<PvcCore.PvcStream> inputStreams)
        {
            var resultStreams = new List<PvcStream>();
            SwitchParser switchParser = null;

            if (!String.IsNullOrEmpty(this.commandLineSwitches))
            {
                switchParser = new SwitchParser();
                switchParser.Parse(this.commandLineSwitches);
            }

            foreach (var inputStream in inputStreams)
            {
                var dirName = Path.GetDirectoryName(inputStream.StreamName);
                var fileName = Path.GetFileNameWithoutExtension(inputStream.StreamName) + ".min" + Path.GetExtension(inputStream.StreamName);
                var resultName = Path.Combine(dirName, fileName);
                var fileContent = new StreamReader(inputStream).ReadToEnd();
                var minifier = new Minifier();
                var sourceStream = new MemoryStream();
                var outputWriter = new StreamWriter(sourceStream);

                if (inputStream.StreamName.EndsWith(".js"))
                {
                    // Currently AjaxMin only supports JS source maps
                    if (this.generateSourceMaps)
                    {
                        var resultMapName = resultName + ".map";
                        var utf8 = new UTF8Encoding(false);
                        var mapStream = new MemoryStream();
                        var mapWriter = new SourcemapStreamWriter(mapStream, utf8);
                        var sourceMap = new V3SourceMap(mapWriter);

                        if (sourceMap != null)
                        {
                            if (switchParser == null)
                            {
                                switchParser = new SwitchParser();
                            }

                            switchParser.JSSettings.SymbolsMap = sourceMap;
                            switchParser.JSSettings.TermSemicolons = true;

                            sourceMap.StartPackage(resultName, resultMapName);

                            outputWriter.Write(minifier.MinifyJavaScript(fileContent, switchParser.JSSettings));

                            sourceMap.EndPackage();
                            sourceMap.EndFile(outputWriter, "\r\n");

                            sourceMap.Dispose();
                            mapWriter.Flush();

                            resultStreams.Add(new PvcStream(() => mapStream).As(resultMapName));
                        }
                    }
                    else
                    {
                        CodeSettings settings = new CodeSettings();
                        if (switchParser != null)   settings = switchParser.JSSettings;
                        outputWriter.Write(minifier.MinifyJavaScript(fileContent, settings));
                    }
                }
                else
                {
                    CssSettings settings = new CssSettings();
                    if (switchParser != null) settings = switchParser.CssSettings;
                    outputWriter.Write(minifier.MinifyStyleSheet(fileContent, settings));
                }

                foreach (var error in minifier.ErrorList)
                {
                    Console.Error.WriteLine(error.ToString());
                }

                outputWriter.Flush();
                resultStreams.Add(new PvcStream(() => sourceStream).As(resultName));
            }

            return resultStreams;
        }