/// <summary>
		/// "Compiles" a JS-code
		/// </summary>
		/// <param name="content">Text content written on JavaScript</param>
		/// <param name="path">Path to JS-file</param>
		/// <param name="externsDependencies">List of JS-externs dependencies</param>
		/// <param name="options">Compilation options</param>
		/// <returns>Compiled JS-code</returns>
		public string Compile(string content, string path, DependencyCollection externsDependencies,
			RemoteJsCompilationOptions options = null)
		{
			string newContent;
			DependencyCollection allExternsDependencies = new DependencyCollection();
			RemoteJsCompilationOptions currentOptions;
			IList<FormItem> currentOptionsFormItems;

			if (options != null)
			{
				currentOptions = options;
				currentOptionsFormItems = ConvertCompilationOptionsToFormItems(currentOptions);
			}
			else
			{
				currentOptions = _defaultOptions;
				currentOptionsFormItems = _defaultOptionsFormItems;
			}

			var formItems = new List<FormItem>();
			formItems.Add(new FormItem("js_code", content));
			if (currentOptions.CompilationLevel == CompilationLevel.Advanced
				&& (_commonExternsDependencies.Count > 0 || externsDependencies.Count > 0))
			{
				allExternsDependencies.AddRange(_commonExternsDependencies);

				foreach (Dependency externsDependency in externsDependencies)
				{
					if (!_commonExternsDependencies.ContainsUrl(externsDependency.Url))
					{
						allExternsDependencies.Add(externsDependency);
					}
				}

				foreach (Dependency externsDependency in allExternsDependencies)
				{
					formItems.Add(new FormItem("js_externs", externsDependency.Content));
				}
			}
			formItems.AddRange(currentOptionsFormItems);

			HttpContent httpContent = new CustomFormUrlEncodedContent(formItems);

			using (var client = new HttpClient())
			{
				HttpResponseMessage response;
				try
				{
					response = client
						.PostAsync(new Uri(_closureCompilerServiceUrl), httpContent)
						.Result
						;
				}
				catch (AggregateException e)
				{
					Exception innerException = e.InnerException;
					if (innerException != null)
					{
						if (innerException is HttpRequestException)
						{
							throw new Exception(
								string.Format(Strings.Minifiers_ClosureRemoteMinificationHttpRequestError,
									_closureCompilerServiceUrl),
								innerException);
						}

						throw innerException;
					}

					throw;
				}

				if (response.IsSuccessStatusCode)
				{
					var result = response.Content.ReadAsStringAsync().Result;
					var json = JObject.Parse(result);

					var serverErrors = json["serverErrors"] != null ? json["serverErrors"] as JArray : null;
					if (serverErrors != null && serverErrors.Count > 0)
					{
						throw new ClosureCompilingException(
							FormatErrorDetails(serverErrors[0], ErrorType.ServerError, path, allExternsDependencies)
						);
					}

					var errors = json["errors"] != null ? json["errors"] as JArray : null;
					if (errors != null && errors.Count > 0)
					{
						throw new ClosureCompilingException(
							FormatErrorDetails(errors[0], ErrorType.Error, path, allExternsDependencies)
						);
					}

					if (currentOptions.Severity > 0)
					{
						var warnings = json["warnings"] != null ? json["warnings"] as JArray : null;
						if (warnings != null && warnings.Count > 0)
						{
							throw new ClosureCompilingException(
								FormatErrorDetails(warnings[0], ErrorType.Warning, path, allExternsDependencies)
							);
						}
					}

					newContent = json.Value<string>("compiledCode");
				}
				else
				{
					throw new AssetMinificationException(
						string.Format(Strings.Minifiers_ClosureRemoteMinificationInvalidHttpStatus,
							response.StatusCode));
				}
			}

			return newContent;
		}
示例#2
0
        /// <summary>
        /// "Compiles" a JS code
        /// </summary>
        /// <param name="content">Text content written on JS</param>
        /// <param name="path">Path to JS file</param>
        /// <param name="externsDependencies">List of JS externs dependencies</param>
        /// <returns>Compiled JS code</returns>
        public string Compile(string content, string path, DependencyCollection externsDependencies)
        {
            string newContent;
            int    commonExternsDependencyCount     = _commonExternsDependencies.Count;
            string assetExternsTempDirectoryPath    = Path.Combine(_tempDirectoryPath, Guid.NewGuid().ToString());
            bool   assetExternsTempDirectoryCreated = false;

            var           stringBuilderPool = StringBuilderPool.Shared;
            StringBuilder argsBuilder       = stringBuilderPool.Rent();

            argsBuilder.AppendFormat(@"-jar ""{0}"" ", _closureCompilerAppPath);
            if (_options.CompilationLevel == CompilationLevel.Advanced &&
                (commonExternsDependencyCount > 0 || externsDependencies.Count > 0))
            {
                if (!_commonExternsTempDirectoryCreated && commonExternsDependencyCount > 0)
                {
                    WriteExternsToTempDirectory(_commonExternsDependencies, out _commonExternsTempDirectoryPath,
                                                out _commonExternsTempFilePaths);
                    _commonExternsTempDirectoryCreated = true;
                }

                DependencyCollection assetExternsDependencies = new DependencyCollection();
                if (commonExternsDependencyCount > 0)
                {
                    foreach (Dependency externsDependency in externsDependencies)
                    {
                        if (!_commonExternsDependencies.ContainsUrl(externsDependency.Url))
                        {
                            assetExternsDependencies.Add(externsDependency);
                        }
                    }
                }
                else
                {
                    assetExternsDependencies.AddRange(externsDependencies);
                }

                IList <string> assetExternsTempFilePaths = new List <string>();

                if (assetExternsDependencies.Count > 0)
                {
                    WriteExternsToTempDirectory(assetExternsDependencies, out assetExternsTempDirectoryPath,
                                                out assetExternsTempFilePaths);
                    assetExternsTempDirectoryCreated = true;
                }

                var allExternsTempFilePaths = new List <string>();
                allExternsTempFilePaths.AddRange(_commonExternsTempFilePaths);
                allExternsTempFilePaths.AddRange(assetExternsTempFilePaths);

                foreach (string externsTempFilePath in allExternsTempFilePaths)
                {
                    argsBuilder.AppendFormat(@"--externs ""{0}"" ", externsTempFilePath);
                }
            }
            argsBuilder.Append(_optionsString);

            string args = argsBuilder.ToString();

            stringBuilderPool.Return(argsBuilder);

            var processInfo = new ProcessStartInfo
            {
                FileName               = _javaVmPath,
                Arguments              = args,
                CreateNoWindow         = true,
                WindowStyle            = ProcessWindowStyle.Hidden,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
            };

            var     stdOutputBuilder = new StdContentBuilder();
            var     stdErrorBuilder  = new StdContentBuilder();
            Process process          = null;

            try
            {
                process = new Process
                {
                    StartInfo = processInfo
                };
                process.OutputDataReceived += stdOutputBuilder.OnDataReceived;
                process.ErrorDataReceived  += stdErrorBuilder.OnDataReceived;

                process.Start();

                using (StreamWriter inputWriter = process.StandardInput)
                {
                    inputWriter.Write(content);
                    inputWriter.Flush();
                }

                process.BeginErrorReadLine();
                process.BeginOutputReadLine();

                process.WaitForExit();

                process.OutputDataReceived -= stdOutputBuilder.OnDataReceived;
                process.ErrorDataReceived  -= stdErrorBuilder.OnDataReceived;

                string errorString = stdErrorBuilder.Content;
                if (!string.IsNullOrWhiteSpace(errorString))
                {
                    IList <string> errors;
                    IList <string> warnings;

                    ParseErrorDetails(errorString, path, out errors, out warnings);

                    if (errors.Count > 0 || warnings.Count > 0)
                    {
                        if (errors.Count > 0)
                        {
                            throw new ClosureCompilationException(errors[0]);
                        }

                        if (_options.Severity > 0 && warnings.Count > 0)
                        {
                            throw new ClosureCompilationException(warnings[0]);
                        }
                    }
                }

                newContent = stdOutputBuilder.Content;
            }
            finally
            {
                if (process != null)
                {
                    process.Dispose();
                }

                stdErrorBuilder.Dispose();
                stdOutputBuilder.Dispose();

                if (assetExternsTempDirectoryCreated && Directory.Exists(assetExternsTempDirectoryPath))
                {
                    Directory.Delete(assetExternsTempDirectoryPath, true);
                }
            }

            return(newContent);
        }
        /// <summary>
        /// "Compiles" a TypeScript-code to JS-code
        /// </summary>
        /// <param name="content">Text content written on TypeScript</param>
        /// <param name="path">Path to TypeScript-file</param>
        /// <param name="dependencies">List of dependencies</param>
        /// <param name="options">Compilation options</param>
        /// <returns>Translated TypeScript-code</returns>
        public string Compile(string content, string path, DependencyCollection dependencies,
            CompilationOptions options = null)
        {
            string newContent;
            CompilationOptions currentOptions;
            string currentOptionsString;

            if (options != null)
            {
                currentOptions = options;
                currentOptionsString = ConvertCompilationOptionsToJson(options).ToString();
            }
            else
            {
                currentOptions = _defaultOptions;
                currentOptionsString = _defaultOptionsString;
            }

            var newDependencies = new DependencyCollection();
            if (!currentOptions.NoLib)
            {
                string defaultLibFileName = (currentOptions.Target == TargetMode.EcmaScript6) ?
                    DEFAULT_LIBRARY_ES6_FILE_NAME : DEFAULT_LIBRARY_FILE_NAME;
                var defaultLibDependency = new Dependency(defaultLibFileName, _commonTypesDefinitions[defaultLibFileName]);
                newDependencies.Add(defaultLibDependency);
            }
            newDependencies.AddRange(dependencies);

            lock (_compilationSynchronizer)
            {
                Initialize();

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

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

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

            return newContent;
        }
示例#4
0
        /// <summary>
        /// "Compiles" a JS code
        /// </summary>
        /// <param name="content">Text content written on JS</param>
        /// <param name="path">Path to JS file</param>
        /// <param name="externsDependencies">List of JS externs dependencies</param>
        /// <returns>Compiled JS code</returns>
        public string Compile(string content, string path, DependencyCollection externsDependencies)
        {
            string newContent;
            DependencyCollection allExternsDependencies = new DependencyCollection();

            var formItems = new List <FormItem>();

            formItems.Add(new FormItem("js_code", content));
            if (_options.CompilationLevel == CompilationLevel.Advanced &&
                (_commonExternsDependencies.Count > 0 || externsDependencies.Count > 0))
            {
                allExternsDependencies.AddRange(_commonExternsDependencies);

                foreach (Dependency externsDependency in externsDependencies)
                {
                    if (!_commonExternsDependencies.ContainsUrl(externsDependency.Url))
                    {
                        allExternsDependencies.Add(externsDependency);
                    }
                }

                foreach (Dependency externsDependency in allExternsDependencies)
                {
                    formItems.Add(new FormItem("js_externs", externsDependency.Content));
                }
            }
            formItems.AddRange(_optionsFormItems);

            HttpContent httpContent = new CustomFormUrlEncodedContent(formItems);

            using (var client = new HttpClient())
            {
                HttpResponseMessage response;
                try
                {
                    response = client
                               .PostAsync(new Uri(_closureCompilerServiceUrl), httpContent)
                               .Result
                    ;
                }
                catch (AggregateException e)
                {
                    Exception innerException = e.InnerException;
                    if (innerException != null)
                    {
                        if (innerException is HttpRequestException)
                        {
                            throw new Exception(
                                      string.Format(Strings.Minifiers_ClosureRemoteMinificationHttpRequestError,
                                                    _closureCompilerServiceUrl),
                                      innerException);
                        }

                        throw innerException;
                    }

                    throw;
                }

                if (response.IsSuccessStatusCode)
                {
                    var result = response.Content.ReadAsStringAsync().Result;
                    var json   = JObject.Parse(result);

                    var serverErrors = json["serverErrors"] != null ? json["serverErrors"] as JArray : null;
                    if (serverErrors != null && serverErrors.Count > 0)
                    {
                        throw new ClosureCompilationException(
                                  FormatErrorDetails(serverErrors[0], ErrorType.ServerError, path, allExternsDependencies)
                                  );
                    }

                    var errors = json["errors"] != null ? json["errors"] as JArray : null;
                    if (errors != null && errors.Count > 0)
                    {
                        throw new ClosureCompilationException(
                                  FormatErrorDetails(errors[0], ErrorType.Error, path, allExternsDependencies)
                                  );
                    }

                    if (_options.Severity > 0)
                    {
                        var warnings = json["warnings"] != null ? json["warnings"] as JArray : null;
                        if (warnings != null && warnings.Count > 0)
                        {
                            throw new ClosureCompilationException(
                                      FormatErrorDetails(warnings[0], ErrorType.Warning, path, allExternsDependencies)
                                      );
                        }
                    }

                    newContent = json.Value <string>("compiledCode");
                }
                else
                {
                    throw new AssetMinificationException(
                              string.Format(Strings.Minifiers_ClosureRemoteMinificationInvalidHttpStatus,
                                            response.StatusCode));
                }
            }

            return(newContent);
        }
		/// <summary>
		/// "Compiles" a JS-code
		/// </summary>
		/// <param name="content">Text content written on JavaScript</param>
		/// <param name="path">Path to JS-file</param>
		/// <param name="externsDependencies">List of JS-externs dependencies</param>
		/// <param name="options">Compilation options</param>
		/// <returns>Compiled JS-code</returns>
		public string Compile(string content, string path, DependencyCollection externsDependencies,
			LocalJsCompilationOptions options = null)
		{
			string newContent;
			int commonExternsDependencyCount = _commonExternsDependencies.Count;
			string assetExternsTempDirectoryPath = Path.Combine(_tempDirectoryPath, Guid.NewGuid().ToString());
			bool assetExternsTempDirectoryCreated = false;
			LocalJsCompilationOptions currentOptions;
			string currentOptionsString;

			if (options != null)
			{
				currentOptions = options;
				currentOptionsString = ConvertCompilationOptionsToArgs(options);
			}
			else
			{
				currentOptions = _defaultOptions;
				currentOptionsString = _defaultOptionsString;
			}

			var args = new StringBuilder();
			args.AppendFormat(@"-jar ""{0}"" ", _closureCompilerAppPath);
			if (currentOptions.CompilationLevel == CompilationLevel.Advanced
				&& (commonExternsDependencyCount > 0 || externsDependencies.Count > 0))
			{
				if (!_commonExternsTempDirectoryCreated && commonExternsDependencyCount > 0)
				{
					WriteExternsToTempDirectory(_commonExternsDependencies, out _commonExternsTempDirectoryPath,
						out _commonExternsTempFilePaths);
					_commonExternsTempDirectoryCreated = true;
				}

				DependencyCollection assetExternsDependencies = new DependencyCollection();
				if (commonExternsDependencyCount > 0)
				{
					foreach (Dependency externsDependency in externsDependencies)
					{
						if (!_commonExternsDependencies.ContainsUrl(externsDependency.Url))
						{
							assetExternsDependencies.Add(externsDependency);
						}
					}
				}
				else
				{
					assetExternsDependencies.AddRange(externsDependencies);
				}

				IList<string> assetExternsTempFilePaths = new List<string>();

				if (assetExternsDependencies.Count > 0)
				{
					WriteExternsToTempDirectory(assetExternsDependencies, out assetExternsTempDirectoryPath,
						out assetExternsTempFilePaths);
					assetExternsTempDirectoryCreated = true;
				}

				var allExternsTempFilePaths = new List<string>();
				allExternsTempFilePaths.AddRange(_commonExternsTempFilePaths);
				allExternsTempFilePaths.AddRange(assetExternsTempFilePaths);

				foreach (string externsTempFilePath in allExternsTempFilePaths)
				{
					args.AppendFormat(@"--externs ""{0}"" ", externsTempFilePath);
				}
			}
			args.Append(currentOptionsString);

			var processInfo = new ProcessStartInfo
			{
				FileName = _javaVmPath,
				Arguments = args.ToString(),
				CreateNoWindow = true,
				WindowStyle = ProcessWindowStyle.Hidden,
				UseShellExecute = false,
				RedirectStandardInput = true,
				RedirectStandardOutput = true,
				RedirectStandardError = true,
			};

			var stdOutputBuilder = new StdContentBuilder();
			var stdErrorBuilder = new StdContentBuilder();
			Process process = null;

			try
			{
				process = new Process
				{
					StartInfo = processInfo
				};
				process.OutputDataReceived += stdOutputBuilder.OnDataReceived;
				process.ErrorDataReceived += stdErrorBuilder.OnDataReceived;

				process.Start();

				using (StreamWriter inputWriter = process.StandardInput)
				{
					inputWriter.Write(content);
					inputWriter.Flush();
				}

				process.BeginErrorReadLine();
				process.BeginOutputReadLine();

				process.WaitForExit();

				process.OutputDataReceived -= stdOutputBuilder.OnDataReceived;
				process.ErrorDataReceived -= stdErrorBuilder.OnDataReceived;

				string errorString = stdErrorBuilder.Content;
				if (!string.IsNullOrWhiteSpace(errorString))
				{
					IList<string> errors;
					IList<string> warnings;

					ParseErrorDetails(errorString, path, out errors, out warnings);

					if (errors.Count > 0 || warnings.Count > 0)
					{
						if (errors.Count > 0)
						{
							throw new ClosureCompilingException(errors[0]);
						}

						if (currentOptions.Severity > 0 && warnings.Count > 0)
						{
							throw new ClosureCompilingException(warnings[0]);
						}
					}
				}

				newContent = stdOutputBuilder.Content;
			}
			finally
			{
				if (process != null)
				{
					process.Dispose();
				}

				if (assetExternsTempDirectoryCreated && Directory.Exists(assetExternsTempDirectoryPath))
				{
					Directory.Delete(assetExternsTempDirectoryPath, true);
				}
			}

			return newContent;
		}